<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;


use app\mill\builder\Admin;
use app\mill\builder\ZBuilder;
use app\common\model\Auth;
use app\user\model\User as UserModel;
use app\mill\model\Client as ClientModel;
use app\mill\model\Give as GiveModel;
use app\mill\model\Order as OrderModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Address as AddressModel;
use app\mill\model\Finance as FinanceModel;
use app\mill\model\Car as CarModel;
use app\mill\model\Stat as StatModel;
use app\mill\model\Db2 as Db2Model;
use app\admin\model\Config as ConfigModel;
use think\Db;

/**
 * 工程控制器
 * @package app\admin\controller
 */
class Order extends Admin
{

    //初始化
    protected function initialize(){
        parent::initialize();
        GiveModel::init();
    }
    //首页
    public function index(){

        $option = "{
                        legend: {
                            data: ['新增工程数']
                        },
                        tooltip: {
                            trigger: 'axis',//鼠标浮动效果
                        },
                        xAxis: {
                            type: 'category',
                            data: data.head
                        },
                        grid: {
                            left: '15',
                            right: '15',
                            bottom: '0',
                            top:'30',
                            containLabel: true
                        },
                        yAxis: {
                            type: 'value',
                            axisLine: {
                                show: false  // 取消纵坐标的标线
                            },
                            axisTick: {
                                show: false  // 取消纵坐标的刻度线
                            },
                            splitLine: {
                                show: false
                            }
                        },
                        series: [
                            {
                                name: '新增工程数',
                                data: data.data,
                                type: 'bar',
                                barWidth:48,
                                itemStyle:{
                                    color:'#276CDE'
                                }
                            }
                        ]
                    }";
        $url = url('mill/stat/ajaxOrder');
        $top_html = StatModel::topStatHtml($url,$option,['year','charts','rank']);

        //获取菜单列表
        $menu = StatModel::getMenu('mill',357);
        //额外HTML代码
        $extra_html = StatModel::fixedHtml($menu);

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('') // 页面标题
            ->setTableName('mill_client') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            ->setExtraHtml($extra_html)
            ->fetch(); // 渲染模板
    }
    //工程列表
    public function lists()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $client_id = input('client_id');
        // 获取查询条件
        $map = $this->getMap();
        if(!empty($client_id))$map[] = ['o.client_id','=',$client_id];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,s.staff as sales,c.company')
            ->leftJoin('mill_client c','o.client_id=c.id')
            ->leftJoin('mill_staff s','o.sales_id=s.id')
            ->where($map)
            ->group('o.order_pid')
            ->order('o.order_pid desc')
            ->paginate()
            ->each(function ($v){

                $v['engineering'] = $v['engineering'].ClientModel::getTags($v);
                //预估余量
                $v['area_sum'] = '';
                //增加批次
                $v['add_order'] = '<a title="增加批次" icon="fa fa-plus-circle" class="btn btn-default pop" href="'.url('mill/order/add',['_pop'=>1,'order_pid'=>$v['id']]).'" float="left" data-layer="{&quot;area&quot;:[&quot;50%&quot;,&quot;50%&quot;],&quot;title&quot;:[&quot;增加批次&quot;,&quot;color:#266CDE&quot;]}"><i class="fa fa-plus-circle"></i> 增加批次</a>';

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('工程列表('.$data_list->total().')') // 页面标题
            ->setTableName('mill_order') // 设置表名
            //->hideCheckbox()
            ->setSearch(['o.engineering' => '工程名称', 'o.archives_sn' => '档案号', 'c.company' => '客户名称', 'o.back' => '内勤']) // 设置搜索参数
            ->setSearchArea([
                ['daterange:2', 'c.create_time', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['engineering', '工程名称','jump_bottom','','order_pid=__order_pid__','badge-warning must',['group'=>'客户信息']],
                ['company', '客户名称','','','','must',['group'=>'客户信息']],
                ['contract', '合同','files','','','must',['group'=>'客户信息']],
                ['back', '内勤','','','','',['group'=>'客户信息']],
                ['money_str','定金状态','','','','',['group'=>'客户信息']],
                ['create_time', '合同日期','date','','','',['group'=>'工程信息']],
                ['create_time', '建立日期','date','','','',['group'=>'工程信息']],
                ['area_sum', '预估余量(m²)','','','','',['group'=>'工程信息']],
                ['note', '备注','','','','badge-warning',['group'=>'其他信息']],
                ['add_order', '增加批次','','','','badge-warning',['group'=>'其他信息']],
                ['is_lock','冻结','switch2','','','badge-warning',['group'=>'其他信息']],
            ])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->addTopButton('add',['title' => '新增工程','href'=>url('mill/order/add'),'class'=>'btn btn-default','float'=>'left'])
            ->addTopButton('edit',['title' => '修改工程','href'=>url('mill/order/add'),'class'=>'btn btn-default js-get'])
            ->addTopButton('delete',['title' => '删除工程'],false)
            ->addTopButton('isLock',['title' => '工程冻结','href'=>url('mill/order/isLock'),'class'=>'btn btn-danger ajax-post confirm'],false)
            ->addTopButton('change',['title' => '工程继承','href'=>url('mill/order/change'),'class'=>'btn btn-default'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 130,
                'mobile'  => 130,
                'sales'  => 130,
                'back'  => 80,
                'money_str'  => 80,
                //'engineering'  => 200,
                //'company'  => 150,
                'add_order'  => 70,
                'is_lock'  => 90,
                'create_time'  => 80,
                'area_sum'  => 80,
            ])
            ->fetch(); // 渲染模板
    }
    //客户列表
    public function clientList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('mill_client')
            ->alias('c')
            ->field('c.*,s.staff as sales,count(o.id) as order_sum')
            ->leftJoin('mill_order o','o.client_id=c.id')
            ->leftJoin('mill_staff s','c.sales_id=s.id')
            ->where($map)
            ->group('c.id')
            ->order('c.id desc')
            ->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('客户列表('.$data_list->total().')') // 页面标题
            ->setTableName('mill_client') // 设置表名
            //->hideCheckbox()
            ->setSearch(['c.company' => '客户名称', 'o.engineering' => '工程名称', 's.staff' => '业务经理']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['company', '客户名称','jump_right','','client_id=__id__','badge-green',['group'=>'客户信息']],
                ['sales', '业务经理','','','','',['group'=>'客户信息']],
                ['order_sum', '工程数','','','','',['group'=>'客户信息']],
            ])
            ->addTopButton('add',['title' => '新增客户','href'=>url('mill/client/add'),'class'=>'btn btn-danger','float'=>'left'])
            ->addTopButton('add',['title' => '新增客户工程','href'=>url('mill/order/add'),'class'=>'btn btn-default dch-js-get','target-form'=>'client_id'])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->setRowList($data_list) // 设置表格数据
            ->setWidth('20%') // 设置表格宽度
            ->setColumnWidth([
                'id'  => 60,
                //'company'  => 130,
                'sales'  => 60,
                'order_sum'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    //新增
    public function add()
    {
        $id = input('ids');
        if (strpos($id, ',') !== false)$this->error('暂不支持批量修改');
        $info = [];

        if ($this->request->isPost()) {
            $data = input();
            //自动生成工程编号
            //if(empty($data['order_sn']))$data['order_sn'] = OrderModel::orderSn();

            // 验证
            $result = $this->validate($data, 'Order');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);
            //判断工程号是否存在
            //if(empty($re['id']) && !empty($re['order_sn'])){
            //    $order_sn = Db::name('mill_order')->where(['order_sn'=>$re['order_sn']])->value('order_sn');
            //    if(!empty($order_sn))$this->error('该工程号已存在');
            //}

            $data['create_time'] = empty($data['create_time'])?time():strtotime($data['create_time']);
            $data['update_time'] = time();

            if($id){
                $order_pid = Db::name('mill_order')->where(['id'=>$id])->value('order_pid');
                $re = Db::name('mill_order')->where(['order_pid'=>$order_pid])->update($data);

                //TODO 同步更新至旧数据库
                Db2Model::orderEdit($id,$data);
            }
            else{
                $re = OrderModel::create($data);
                $id = $re['id'];
                if ($re)OrderModel::update(['order_pid'=>$id],['id'=>$id]);

                //TODO 同步更新至旧数据库
                Db2Model::orderEdit($id,$data,true);
            }

            if ($re)$this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        //客户信息
        $client_id = input('client_id');
        if (strpos($client_id, ',') !== false)$this->error('客户信息只能选一个');
        $client = ClientModel::get($client_id);
        if(!empty($client['id'])){
            $info['client_id'] = $client['id'];
            $info['back_id'] = $client['back_id'];
            $info['sales_id'] = $client['sales_id'];
            $info['mill_id'] = $client['mill_id'];
        }
        //总工程信息
        $order_pid = input('order_pid');
        if($order_pid){
            $order = Db::name('mill_order')->where(['id'=>$order_pid])->find();
            $info['client_id'] = $order['client_id'];
            $info['back_id'] = $order['back_id'];
            $info['sales_id'] = $order['sales_id'];
            $info['mill_id'] = $order['mill_id'];
            $info['order_pid'] = $order['order_pid'];
            $info['money_str'] = $order['money_str'];
        }
        //编辑
        if($id)$info = Db::name('mill_order')->where(['id'=>$id])->find();

        //获取内勤
        $back_list = ClientModel::getStaffList(2);
        //获取所有客户
        $client_list = ClientModel::getList('company');
        //获取所有客户
        $list = ClientModel::getList('*');
        //js
        $js = '<script type="text/javascript">
                $(function(){
                    var client_list = '.json_encode($list,JSON_UNESCAPED_UNICODE).';
                    $("#client_id").change(function(){
                    var client_id = $(this).children("option:selected").val();
                    var client = client_list[client_id];
                    if(client){
                        $("#back").val(client.back);
                        $("#back_id").val(client.back_id).trigger("change");  // 动态更改值;
                        $("#sales").val(client.sales);
                        $("#sales_id").val(client.sales_id);
                        $("#mill_id").val(client.mill_id);
                    }
                    else{
                        $("#back").val("");
                        $("#back_id").val("").trigger("change");  // 动态更改值;
                        $("#sales").val("");
                        $("#sales_id").val("");
                        $("#mill_id").val("");
                    }
                    
                    })
                });
            </script>';

        return ZBuilder::make('form')
            ->setPageTitle('新增客户工程') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['ititle', 'ititle1', '工程项'],
                ['ititle', 'ititle2', '公司项'],
                ['text:||||must', 'engineering', '工程名称'],
                ['select', 'money_str', '订金状态','',['未付'=>'未付','已付'=>'已付','无定金'=>'无定金'],'未付'],
                ['select:||||must', 'client_id', '选择客户[:请选择客户]', '', $client_list],
                ['select', 'back_id', '内勤人员', '', $back_list],
                ['text', 'waiback_open', '工程联系'],
                ['date', 'create_time', '合同日期','',date('Y-m-d')],
                ['select', 'point', '优先级','',ClientModel::$point,0],
                ['file', 'contract', '合同上传'],
                ['hidden', 'back'],
                ['hidden', 'sales'],
                ['hidden', 'sales_id'],
                ['hidden', 'mill_id'],
                ['hidden', 'order_pid'],
                //['text', 'archives_sn', '档案号'],
                //['text', 'batch', '批次'],
                ['textarea', 'note', '备注'],
            ])
            ->setFormData($info)
            ->layout(['note'=>12])
            ->setExtraJs($js)
            ->fetch();
    }
    //内勤继承
    public function change($type = 1){

        $page_title_arr = [
            'title'     =>  '内勤继承',
            'title2'     =>  '移交选项',
            'title3'     =>  '移交人',
            'title4'     =>  '接收人',
        ];
        if($type == 2){
            $page_title_arr = [
                'title'     =>  '内勤归属',
                'title2'     =>  '归属选项',
                'title3'     =>  '客户原归属',
                'title4'     =>  '客户归属给',
            ];
        }

        if ($this->request->isPost()) {
            $data = input();

            if(empty($data['staff_id'])) $this->error('请选择'.$page_title_arr['title3']);
            if(empty($data['staff_id2'])) $this->error('请选择'.$page_title_arr['title4']);
            if(empty($data['ids'])) $this->error('请选择移交工程');

            $ids = implode($data['ids'],',');

            $re = Db::name('mill_order')->where([['order_pid','in',$ids]])->update(['sales_id'=>$data['staff_id2']]);

            //关闭子窗口，并刷新父窗口
            if ($re)$this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        $staff_list = ClientModel::getStaffList(1);

        $table_arr = OrderModel::fromOrderPSelect();
        $layui_head = $table_arr['layui_head'];
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        $js = '<script type="text/javascript">
                
                //移交人点击事件
                $("body").on("change","select[name=\'staff_id\']",function(){
                    var id = $(this).val();
                    
                    $.ajax({
                        url: \''.url("mill/order/changeList").'?type='.$type.'&staff_id=\'+id,
                        type: \'GET\'
                    }).done(function(data) {
                    
                        form_table_tbody(data);
                        
                    })
                    
                });
                //接收人点击事件
                $("body").on("change","select[name=\'staff_id2\']",function(){
                    var name = $(this).attr("name");
                    var id = $(this).val();
                    var title = id?$("#select2-"+name+"-container").attr("title"):"";
                    
                    $("td[data-field=\'do_id\']").find("div").html(title);
                    
                });
            </script>';

        return ZBuilder::make('form')
            ->setPageTitle($page_title_arr['title']) // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['ititle:12', 'ititle1', $page_title_arr['title2']],
                ['select', 'staff_id', $page_title_arr['title3'],'',$staff_list],
                ['select', 'staff_id2', $page_title_arr['title4'],'',$staff_list],
                ['complexTable2:12', 'order_list', '', $table_data, $table_head ,$layui_head,'','400'],
            ])
            ->setExtraJs($js)
            ->fetch();
    }
    //内勤继承
    public function changeList($type = 1){

        $staff_id = input('staff_id');

        $where = [];
        if($type == 1)$where = ['o.sales_id'=>$staff_id];
        else if($type == 2)$where = ['o.sales_id'=>$staff_id];

        $list = [];
        if($staff_id){
            $list = Db::name('mill_order')
                ->alias('o')
                ->field('o.*,staff as sales,count(o.batch) as batch_sum,sum(a.row_area) as area_sum')
                ->leftJoin('mill_staff s','o.sales_id=s.id')
                ->leftJoin('mill_order_archives a','a.order_id=o.id')
                ->where($where)
                ->group('o.order_pid')
                ->order('o.order_pid desc')
                ->select();
        }

        $table_arr = OrderModel::fromOrderPSelect(['list'=>$list]);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        $tbody = '';
        if(!empty($table_data)){
            foreach ($table_data as $tdv){
                $tr = '<tr>';
                foreach ($tdv as $tdvv){
                    $tr .= '<td>'.$tdvv.'</td>';
                }
                $tr .='</tr>';

                $tbody .= $tr;
            }
        }

        exit($tbody);
    }
    //冻结
    public function isLock($record = [])
    {
        return $this->setStatus('isLock');
    }
    //删除
    public function delete($record = [])
    {
        return $this->setStatus('delete');
    }
    //启用
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }
    //禁用
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }
    /**
     * 设置客户状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        foreach ($ids as $id) {

            $id = Db::name('mill_order')->where(['id'=>$id])->value('order_pid');

            switch ($type) {
                case 'isLock':
                    if (false === OrderModel::where('order_pid', $id)->setField('is_lock', 0)) {
                        $this->error('冻结失败，工程PID：'.$id);
                    }
                    break;
                case 'enable':
                    if (false === OrderModel::where('order_pid', $id)->setField('status', 1)) {
                        $this->error('审核失败，工程PID：'.$id);
                    }
                    break;
                case 'disable':
                    if (false === OrderModel::where('order_pid', $id)->setField('status', -1)) {
                        $this->error('审核失败，工程PID：'.$id);
                    }
                    break;
                case 'delete':

                    OrderModel::orderDelete('order_pid',$id);
                    break;
                default:
                    $this->error('非法操作');
            }

            OrderModel::where('id', $id)->setField('status_verify_uid', UID);
            OrderModel::where('id', $id)->setField('status_time', time());

            action_log('role_'.$type, 'mill', $id, UID);
        }

        $this->success('操作成功');
    }
    //待审核工程列表页
    public function examine()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        //$map[] = ['status','in','0,-1'];
        $map[] = $map0[] = $map01[] = ['o.archives_status','in','2'];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,c.company')
            ->leftJoin('mill_client c','o.client_id=c.id')
            ->where($map)
            ->order('status asc,id desc')
            ->paginate()
            ->each(function ($v){

                $archives = Db::name('mill_order_archives')->field('sum(number) as number_sum,sum(row_area) as area_sum')->where(['order_id'=>$v['id']])->find();

                $v = array_merge($v,$archives);

                $v['archives_sn'] = '<div class="fixedName" data-order-id="'.$v['id'].'">'.$v['archives_sn'].ClientModel::getTags($v).'</div>';

                //开平信息
                $v['give_status_str'] = isset(GiveModel::$give_status[$v['give_status']])?GiveModel::$give_status[$v['give_status']]:'已完成';
                if($v['give_status'] > 0)$v['give_status_str'] .= '中';

                return $v;
            })
        ;
        //待审核
        $map0[] = ['o.status','eq','0'];
        $total0 = Db::name('mill_order')->alias('o')->field('o.*,c.company')->leftJoin('mill_client c','o.client_id=c.id')->where($map0)->count();
        //未通过
        $map01[] = ['o.status','eq','-1'];
        $total01 = Db::name('mill_order')->alias('o')->field('o.*,c.company')->leftJoin('mill_client c','o.client_id=c.id')->where($map01)->count();

        $top_html = StatModel::enableHtml();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('订单审批（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            //->hideCheckbox(true)
            ->setSearch(['o.engineering' => '工程名称', 'o.archives_sn' => '档案号', 'c.company' => '客户名称']) // 设置搜索参数
            ->setSearchArea([
                ['daterange:2', 'back_status_time', '合同签订日期'],
                //['select:2', 'status', '审核状态','','',[0=>'待审核',1=>'已审核',-1=>'未通过']],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案号','','','','',['group'=>'批次列表']],
                ['batch', '批次','','','','',['group'=>'批次列表']],
                ['engineering', '工程名称','','','','',['group'=>'批次列表']],
                ['company','客户名称','','','','',['group'=>'批次列表']],
                ['money_str','订金','','','','',['group'=>'批次列表']],
                ['back','内勤','','','','',['group'=>'批次列表']],
                ['number_sum','数量(件)','','','','',['group'=>'批次列表']],
                ['area_sum','面积(m²)','','','','',['group'=>'批次列表']],
                ['archives_bill_time', '发单日期','date','','','',['group'=>'批次列表']],
                ['create_time', '合同签订日期','date','','','',['group'=>'批次列表']],
                ['archives_bill_time','面积表上传日期','date','','','',['group'=>'批次列表']],
                ['archives_sign_time', '图纸确认日期','date','','','',['group'=>'批次列表']],
                ['give_status_str', '开平状态','','','','',['group'=>'批次列表']],
                ['archives_drawing','面积表','files','','','',['group'=>'其他信息']],
                ['right_button', '审批', 'btn','','','',['group'=>'其他信息']],
            ])
            ->addRightButton('enable',['title' => 'OK','href' => url('mill/order/batchPoint',['id' => '__id__'])."?fieldv=status|1",'class'=>'btn btn- btn-default'],['area' => ['500px', '380px'], 'title' => ['审核通过', 'font-size:24px;text-align: center;']])
            ->addRightButton('notDisable',['title' => 'NO','href' => url('mill/order/notDisable',['id' => '__id__','field'=>'status']),'class'=>'btn btn- btn-default'],['area' => ['500px', '280px'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->replaceRightButton(['status' => ['in', '1']], '', 'enable,notDisable')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'money_str'  => 60,
                'batch'  => 60,
                'back'  => 60,
                'number_sum'  => 60,
                'area_sum'  => 80,
                'archives_bill_time'  => 90,
                'create_time'  => 80,
                'archives_sign_time'  => 80,
                'give_status_str'  => 80,
                'right_button'  => 70,
            ])
            ->fetch(); // 渲染模板

    }
    //审核
    public function backEnable()
    {

        $ids = input('ids');
        $id = input('id');
        if($id)$ids[] = $id;
        if(empty($ids))$this->error('请选择工程');
        $fieldv = input('fieldv');
        $fieldv = explode('|',$fieldv);

        foreach ($ids as $id){
            if (false === OrderModel::where('id', $id)->setField($fieldv[0], $fieldv[1])) {
                $this->error('审核失败，工程ID：'.$id);
            }
            //审核人员
            OrderModel::where('id', $id)->setField($fieldv[0].'_verify_uid', UID);
            //审核时间
            OrderModel::where('id', $id)->setField($fieldv[0].'_time', time());
        }


        $this->success('提交成功', null, '_parent_reload');
    }
    //审核不通过
    public function notDisable()
    {
        $field = input('param.field');
        if ($this->request->isPost()) {
            $data = input();
            $id = input('param.id');
            if (false === OrderModel::where('id', $id)->setField($field, -1)) {
                $this->error('审核失败，工程ID：'.$id);
            }
            if(!empty($data[$field.'_note']))OrderModel::where('id', $id)->setField($field.'_note', $data[$field.'_note']);
            //审核人员
            OrderModel::where('id', $id)->setField($field.'_verify_uid', UID);

            $this->success('操作成功', null, '_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('审核不通过原因') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItems([ // 批量添加表单项
                ['textarea', $field.'_note', '[:请输入审核不通过原因]'],
            ])
            ->layout([$field.'_note'=>12])
            ->fetch();
    }

    //----------------------------------------批次-----------------------------------------------------
    //首页
    public function batchIndex(){

        $option = "{
                        legend: {
                            data: ['新增工程数']
                        },
                        tooltip: {
                            trigger: 'axis',//鼠标浮动效果
                        },
                        xAxis: {
                            type: 'category',
                            data: data.head
                        },
                        grid: {
                            left: '15',
                            right: '15',
                            bottom: '0',
                            top:'30',
                            containLabel: true
                        },
                        yAxis: {
                            type: 'value',
                            axisLine: {
                                show: false  // 取消纵坐标的标线
                            },
                            axisTick: {
                                show: false  // 取消纵坐标的刻度线
                            },
                            splitLine: {
                                show: false
                            }
                        },
                        series: [
                            {
                                name: '新增工程数',
                                data: data.data,
                                type: 'bar',
                                barWidth:48,
                                itemStyle:{
                                    color:'#276CDE'
                                }
                            }
                        ]
                    }";
        $url = url('mill/stat/ajaxOrder');
        $top_html = StatModel::topStatHtml($url,$option,['year','charts','rank']);

        //获取菜单列表
        $menu = StatModel::getMenu('mill',380);
        //额外HTML代码
        $extra_html = StatModel::fixedHtml($menu);

        //额外HTML代码
        $url = url('mill/stat/ajaxbatchspeed');
        $extra_html .= StatModel::orderToSpeedHtml($url);

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('') // 页面标题
            ->setTableName('mill_client') // 设置表名
            ->setExtraHtml($top_html.$extra_html,'block_top')
            //->setExtraHtml($extra_html)
            ->fetch(); // 渲染模板
    }
    //批次列表
    public function batchList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        $order_pid = input('order_pid');
        // 获取查询条件
        $map = $this->getMap();
        if(!empty($order_pid))$map[] = ['o.order_pid','=',$order_pid];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,s.staff as sales,c.company')
            ->leftJoin('mill_client c','o.client_id=c.id')
            ->leftJoin('mill_staff s','o.sales_id=s.id')
            ->where($map)
            ->group('o.id')
            ->order('o.id desc')
            ->paginate()
            ->each(function ($v){

                $archvices = ArchivesModel::getOneStat($v['id'],'order_id');
                $v = array_merge($v,$archvices);

                $v['archives_sn'] = $v['archives_sn'].ClientModel::getTags($v);

                //开平信息
                $v['give_status_str'] = isset(GiveModel::$give_status[$v['give_status']])?GiveModel::$give_status[$v['give_status']]:'已完成';
                if($v['give_status'] > 0)$v['give_status_str'] .= '中';

                //发货金额
                $order_money = OrderModel::orderPrice($v['id']);
                $v = array_merge($v,$order_money);
                //油漆采购
                $v['order_color_sum'] = '';
                //周期
                $v['give_pro'] = empty($v['give_pro'])?'':"{$v['give_pro']}天";
                //计价
                //$v['archives_price'] = '<a class="btn btn-default pop" href="'.url('mill/finance/archivesPrice',['_pop'=>1,'order_id'=>$v['id']]).'" data-layer="{&quot;area&quot;:[&quot;50%&quot;,&quot;50%&quot;],&quot;title&quot;:[&quot;计价&quot;,&quot;color:#266CDE&quot;]}">计价</a>';
                $v['archives_price'] = '<a class="btn btn-default" href="'.url('mill/finance/archivesPrice',['order_id'=>$v['id']]).'">计价</a>';
                //$v['archives_price'] = '<a class="btn btn-default" href="javascript:void(0);">计价</a>';
                $v['show_speed'] = '查看产量';

                return $v;
            })
        ;

        $group_name = '工程列表';

        //获取生产状态字段
        $give_status = GiveModel::$give_status_search;
        unset($give_status[0]);

        $columns2 = [];
        $column_width2 = [];
        foreach ($give_status as $gk=>$gs){
            $columns2[] = ["status{$gk}_no_sum", "待{$gs}(件)",'','','','badge-info',['group'=>'生产情况']];
            $column_width2["status{$gk}_no_sum"] = 53;
        }

        $columns = [ // 批量添加列
            ['archives_sn', '档案号','jump_bottom','','order_id=__id__','badge-warning',['group'=>$group_name]],
            ['engineering', '工程名称','','','','',['group'=>$group_name]],
            ['batch', '批次','','','','',['group'=>$group_name]],
            ['number_sum', '数量(件)','','','','',['group'=>$group_name]],
            ['area_sum', '面积(㎡)','','','','',['group'=>$group_name]],
        ];
        $columns = array_merge($columns,$columns2);
        $columns2 = [
            ['archives_drawing', '面积表','files','','','badge-info',['group'=>'生产情况']],
            ['point_time', '交货时间','date','','','badge-info',['group'=>'生产情况']],
            ['give_status_str', '开平信息','','','','',['group'=>'物料详情']],
            ['order_color_sum', '油漆采购','','','','',['group'=>'物料详情']],
            ['address_price', '发货金额','','','','',['group'=>'工程计价']],
            ['initial_price', '计价','','','','',['group'=>'工程计价']],
            ['give_pro', '周期','','','','',['group'=>'其他信息']],
            ['is_lock','冻结','switch2','','','badge-warning',['group'=>'其他信息']],
            ['show_speed', '操作','jump_top','','order_id=__id__','badge-warning',['group'=>'其他信息']],
        ];
        $columns = array_merge($columns,$columns2);

        $column_width = [
            'id'  => 60,
            'archives_sn'  => 120,
            'engineering'  => 100,
            'archives_drawing'  => 270,
            'number_sum'  => 40,
            'archives_price'  => 42,
            'batch'  => 60,
            'order_color_sum'  => 50,
            'point_time'  => 70,
            'address_price'  => 50,
            'give_pro'  => 40,
            'is_lock'  => 80,
        ];
        $column_width = array_merge($column_width,$column_width2);

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('批次列表('.$data_list->total().')') // 页面标题
            ->setTableName('mill_order') // 设置表名
            //->hideCheckbox()
            ->setSearch(['o.engineering' => '工程名称', 'o.archives_sn' => '档案号', 'c.company' => '客户名称', 'o.back' => '内勤']) // 设置搜索参数
            ->setSearchArea([
                ['radio:5', 'o.mill_id', '','','',ClientModel::getMillList(),'left'],
                ['daterange:2', 'o.create_time', '日期'],
            ])
            ->addColumns($columns)
            ->addTopButton('able',['title' => '清空扫码状态','href'=>url('mill/give/able',['status'=>0]),'class'=>'btn btn-default ajax-post confirm','target-form'=>'order_ids','float'=>'right'],false)
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->addTopButton('batchChange',['title' => '批次调拨','href'=>url('mill/order/batchChange'),'class'=>'btn btn-default'])
            ->addTopButton('batchDelete',['title' => '删除批次','href'=>url('mill/order/batchDelete'),'class'=>'btn btn-danger ajax-post confirm'],false)
            ->addTopButton('batchIsLock',['title' => '批次冻结','href'=>url('mill/order/batchIsLock'),'class'=>'btn btn-danger ajax-post confirm'],false)
            ->addTopButton('batchPoint',['title' => '生产优先级设置','href'=>url('mill/order/batchPoint'),'class'=>'btn btn-default js-get'],['area' => ['500px', '380px'], 'title' => ['生产优先级设置', 'font-size:24px;text-align: center;']])
            ->addTopButton('give',['title' => '产品明细','href'=>url('mill/give/index'),'class'=>'btn btn-default js-get','target-form'=>'order_ids'],false)
            ->addTopButton('archivesEdit',['title' => '修改面积表','href'=>url('mill/order/archivesEdit'),'class'=>'btn btn-default js-get','target-form'=>'id'],false)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth($column_width)
            ->fetch(); // 渲染模板
    }
    //工程列表
    public function orderList()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,s.staff as sales,c.company,count(o.id) as order_sum')
            ->leftJoin('mill_client c','o.client_id=c.id')
            ->leftJoin('mill_staff s','o.sales_id=s.id')
            ->where($map)
            ->group('o.id')
            ->order('o.id desc')
            ->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('工程列表('.$data_list->total().')') // 页面标题
            ->setTableName('mill_order') // 设置表名
            //->hideCheckbox()
            ->setSearch(['o.engineering' => '工程名称', 'o.archives_sn' => '档案号', 'c.company' => '客户名称', 'o.back' => '内勤']) // 设置搜索参数
            ->addColumns([ // 批量添加列
                ['engineering', '工程名称','jump_right','','order_pid=__order_pid__','badge-green',['group'=>'工程信息']],
                ['sales', '业务经理','','','','',['group'=>'工程信息']],
                ['back', '内勤','','','','',['group'=>'工程信息']],
                ['order_sum','批次数量','','','','',['group'=>'工程信息']],
            ])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])
            ->addTopButton('add',['title' => '新增工程','href'=>url('mill/order/add'),'class'=>'btn btn-default','float'=>'left'])
            ->addTopButton('edit',['title' => '修改工程','href'=>url('mill/order/add'),'class'=>'btn btn-default js-get'])
            ->setRowList($data_list) // 设置表格数据
            ->setWidth('20%') // 设置表格宽度
            ->setColumnWidth([
                'id'  => 60,
                'sales'  => 60,
                'back'  => 60,
                'order_sum'  => 50,
            ])
            ->fetch(); // 渲染模板
    }
    //批次调拨
    public function batchChange($type = 1){

        $page_title_arr = [
            'title'     =>  '批次调拨',
            'title2'     =>  '移交选项',
            'title3'     =>  '移交',
            'title4'     =>  '接收',
        ];

        if ($this->request->isPost()) {
            $data = input();

            if(empty($data['order_pid'])) $this->error('请选择'.$page_title_arr['title3']);
            if(empty($data['order_pid2'])) $this->error('请选择'.$page_title_arr['title4']);
            if(empty($data['ids'])) $this->error('请选择移交工程');

            $ids = implode($data['ids'],',');

            $re = Db::name('mill_order')->where([['id','in',$ids]])->update(['order_pid'=>$data['order_pid2']]);

            //关闭子窗口，并刷新父窗口
            if ($re)$this->success('操作成功','','_parent_reload');
            $this->error('操作失败');
        }

        $order_list = OrderModel::getList('engineering','order_pid','order_pid');

        $table_arr = OrderModel::fromOrderSelect();
        $layui_head = $table_arr['layui_head'];
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        $js = '<script type="text/javascript">
                
                //移交人点击事件
                $("body").on("change","select[name=\'order_pid\']",function(){
                    var order_pid = $(this).val();
                    
                    $.ajax({
                        url: \''.url("mill/order/batchChangeList").'?type='.$type.'&order_pid=\'+order_pid,
                        type: \'GET\'
                    }).done(function(data) {
                    
                        form_table_tbody(data);
                        
                    })
                    
                });
                //接收人点击事件
                $("body").on("change","select[name=\'order_pid2\']",function(){
                    var name = $(this).attr("name");
                    var id = $(this).val();
                    var title = id?$("#select2-"+name+"-container").attr("title"):"";
                    
                    $("td[data-field=\'do_id\']").find("div").html(title);
                    
                });
            </script>';

        return ZBuilder::make('form')
            ->setPageTitle($page_title_arr['title']) // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['ititle:12', 'ititle1', $page_title_arr['title2']],
                ['select', 'order_pid', $page_title_arr['title3'],'',$order_list],
                ['select', 'order_pid2', $page_title_arr['title4'],'',$order_list],
                ['complexTable2:12', 'order_list', '', $table_data, $table_head ,$layui_head],
            ])
            ->setExtraJs($js)
            ->fetch();
    }
    //工程继承
    public function batchChangeList($type = 1){

        $order_pid = input('order_pid');

        $where = [];
        if($type == 1)$where = ['o.order_pid'=>$order_pid];

        $list = [];
        if($order_pid){
            $list = Db::name('mill_order')
                ->alias('o')
                ->field("o.*,sum(a.number) as number_sum,sum(a.row_area) as area_sum")
                ->leftJoin('mill_order_archives a','a.order_id=o.id')
                ->where($where)
                ->group('o.id')
                ->order('o.id desc')
                ->select();
        }

        $table_arr = OrderModel::fromOrderSelect(['list'=>$list]);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];

        $tbody = '';
        if(!empty($table_data)){
            foreach ($table_data as $tdv){
                $tr = '<tr>';
                foreach ($tdv as $tdvv){
                    $tr .= '<td>'.$tdvv.'</td>';
                }
                $tr .='</tr>';

                $tbody .= $tr;
            }
        }

        exit($tbody);
    }
    //冻结
    public function batchIsLock($is_lock = '')
    {
        if(!is_numeric($is_lock))$is_lock = input('is_lock',0);

        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        foreach ($ids as $id) {
            if (false === OrderModel::where('id', $id)->setField('is_lock', $is_lock)) $this->error('冻结失败，工程ID：'.$id);
        }

        $this->success('操作成功');
    }
    //解除冻结
    public function batchEnIsLock()
    {
        $this->batchIsLock(0);
    }
    //删除
    public function batchDelete()
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        foreach ($ids as $id) {
            OrderModel::orderDelete('order_id',$id);
        }

        $this->success('操作成功');
    }
    //优先级设置
    public function batchPoint()
    {
        $id = input('ids',input('id'));
        $fieldv = input('fieldv');

        if ($this->request->isPost()) {
            $data = input();
            $data['ids'] = $id;

            if(empty($data['ids']))$this->error('请选择批次');

            $update = [
                'point'             =>  $data['point'],
                'point_time'        =>  !empty($data['point_time'])?strtotime($data['point_time']):'',
            ];
            $re = Db::name('mill_order')->where([['id','in',$data['ids']]])->update($update);
            if ($re){
                if($fieldv)$this->backEnable();
                else $this->success('操作成功','','_parent_reload');
            }
            $this->error('操作失败');
        }

        //工程信息
        $order_title = Db::name('mill_order')->where([['id','in',$id]])->column("concat(engineering,'[',archives_sn,']') as str_name");
        $order_title = implode('，',$order_title);

        return ZBuilder::make('form')
            ->setPageTitle('优先级设置') // 页面标题
            ->addFormItems([ // 批量添加表单项
                ['ititle:12', 'ititle1', $order_title],
                ['date:12', 'point_time', '交货日期','',date('Y-m-d')],
                ['select:12||||must', 'point', '优先级','',ClientModel::$point,0],
            ])
            ->fetch();
    }

    //---------------------------------------面积部----------------------------------------------------
    public function archivesIndexHtml(){
        $option = "{
                        color:['#2478F2','#84B7F9','#5F9CF8','#7F83F7'],
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
            
                        },
                        grid: {
                            left: '10',
                            right: '10',
                            bottom: '20',
                            top: '15',
                        },
                        yAxis: {
                            type: 'value',
                            boundaryGap: [0, 0.01]
                        },
                        xAxis: {
                            type: 'category',
                            data: data.head
                        },
                        series: data.series
                    }";
        $url = url('mill/stat/ajaxOrder2');
        $top_html = StatModel::topStatHtml($url,$option,['charts','year']);

        return $top_html;
    }
    //待上传面积列表页
    public function archives()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        $map[] = ['archives_status','in','0,-1,2'];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,c.company,c.create_time as client_time')
            ->leftJoin('mill_client c','o.client_id=c.id')
            ->where($map)
            ->order('status asc,id desc')
            ->paginate()
            ->each(function ($v){

                $archives = Db::name('mill_order_archives')->field('sum(number) as number_sum,sum(row_area) as area_sum')->where(['order_id'=>$v['id']])->find();

                $v = array_merge($v,$archives);

                if($v['archives_sn'])$v['archives_sn'] = $v['archives_sn'].ClientModel::getTags($v);

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                layui_func["archives"] = function (){
                    $(".archivesEdit_btn").css("display","none");
                    $(".archives_drawing").click(function(){
                        window.location.href = $(this).parents("tr").find("[data-files='."'".'archivesEdit'."'".']").attr("href");
                    })
                };
            </script>';

        $top_html = $this->archivesIndexHtml();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('待上传面积表') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            //->hideCheckbox(true)
            ->setSearch(['o.engineering' => '工程名称', 'o.archives_sn' => '档案号', 'c.company' => '客户名称']) // 设置搜索参数
            ->setSearchArea([
                ['daterange:2', 'back_status_time', '合同签订日期'],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案号','','','','',['group'=>'批次列表']],
                ['batch', '批次','','','','',['group'=>'批次列表']],
                ['engineering', '工程名称','','','','',['group'=>'批次列表']],
                ['company','客户名称','','','','',['group'=>'批次列表']],
                ['money_str','订金','','','','',['group'=>'批次列表']],
                ['back','内勤','','','','',['group'=>'批次列表']],
                ['number_sum','数量(件)','','','','',['group'=>'批次列表']],
                ['area_sum','面积(m²)','','','','',['group'=>'批次列表']],
                ['create_time', '合同签订日期','date','','','',['group'=>'日期信息']],
                ['client_time','客户创建日期','date','','','',['group'=>'日期信息']],
                ['create_time', '工程创建日期','date','','','',['group'=>'日期信息']],
                ['archives_drawing','面积表','files.edit','','','',['group'=>'面积表详情']],
                ['note','备注','','','','',['group'=>'工程备注']],
                ['right_button', '操作', 'btn','','','',['group'=>'操作']],
            ])
            ->setExtraJs($js)
            ->addRightButton('backEnable',['title' => '提交','href' => url('backEnable',['id' => '__id__']).'?fieldv=archives_status|1','class'=>'btn btn-primary disable-dch ajax-get','icon'=>''])
            ->addRightButton('addArchives',['title' => '新增','href' => url('archivesEdit',['order_pid' => '__order_pid__']),'class'=>'btn bg-default disable-dch','icon'=>''],false)
            ->addRightButton('delArchives',['title' => '删除','href' => url('delArchives',['order_id'=>'__id__']),'class'=>'btn btn-danger disable-dch ajax-get confirm','icon'=>''])
            ->addRightButton('archivesEdit',['title' => '上传面积表','href' => url('archivesEdit',['id' => '__id__']),'data-files'=>'archivesEdit','class'=>'archivesEdit_btn','icon'=>''],false)
            ->replaceRightButton(['archives_status' => ['=','2']],'',['backEnable'])
            ->replaceRightButton(['archives_status' => ['<>','2']],'',['archivesGive','addArchives','archivesList'])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'archives_sn'  => 150,
                'engineering'  => 200,
                'company'  => 200,
                'money_str'  => 60,
                'batch'  => 60,
                'back'  => 60,
                'number_sum'  => 60,
                'area_sum'  => 80,
                'create_time'  => 80,
                'client_time'  => 80,
                'right_button'  => 80,
            ])
            ->fetch(); // 渲染模板
    }
    //提交审核
    public function archivesEnable(){
        return $this->backEnable();
    }
    //待审核上传面积表列表页
    public function archivesVerify($archives_status = '1')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        $map[] = ['archives_status','in',$archives_status];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,c.company,c.create_time as client_time')
            ->leftJoin('mill_client c','o.client_id=c.id')
            ->where($map)
            ->order('status asc,id desc')
            ->paginate()
            ->each(function ($v){

                $archives = Db::name('mill_order_archives')->field('sum(number) as number_sum,sum(row_area) as area_sum')->where(['order_id'=>$v['id']])->find();

                $v = array_merge($v,$archives);

                $v['archives_sn'] = '<div class="fixedName" data-order-id="'.$v['id'].'">'.$v['archives_sn'].ClientModel::getTags($v).'</div>';

                return $v;
            })
        ;

        //JS
        $js = '<script type="text/javascript">
                layui_func["archivesVerify"] = function (){
                    $(".archivesEdit_btn").css("display","none");
                    $(".archives_drawing").click(function(){
                        window.location.href = $(this).parents("tr").find("[data-files='."'".'archivesEdit'."'".']").attr("href");
                    })
                };
            </script>';

        $top_html = StatModel::enableHtml();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('待审核面积表') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            //->hideCheckbox(true)
            ->setSearch(['o.engineering' => '工程名称', 'o.archives_sn' => '档案号', 'c.company' => '客户名称']) // 设置搜索参数
            ->setSearchArea([
                ['daterange:2', 'back_status_time', '合同签订日期'],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案号','','','','',['group'=>'批次列表']],
                ['batch', '批次','','','','',['group'=>'批次列表']],
                ['engineering', '工程名称','','','','',['group'=>'批次列表']],
                ['company','客户名称','','','','',['group'=>'批次列表']],
                ['money_str','订金','','','','',['group'=>'批次列表']],
                ['back','内勤','','','','',['group'=>'批次列表']],
                ['number_sum','数量(件)','','','','',['group'=>'批次列表']],
                ['area_sum','面积(m²)','','','','',['group'=>'批次列表']],
                ['create_time', '合同签订日期','date','','','',['group'=>'日期信息']],
                ['client_time','客户创建日期','date','','','',['group'=>'日期信息']],
                ['create_time', '工程创建日期','date','','','',['group'=>'日期信息']],
                ['archives_drawing','面积表','files.edit','','','',['group'=>'面积表详情']],
                ['note','备注','','','','',['group'=>'工程备注']],
                ['right_button', '操作', 'btn','','','',['group'=>'操作']],
            ])
            ->setExtraJs($js)
            ->addRightButton('backEnable',['title' => 'OK','href' => url('mill/order/backEnable',['id' => '__id__'])."?fieldv=archives_status|2",'class'=>'btn btn-default ajax-get'],false)
            ->addRightButton('notDisable',['title' => 'NO','href' => url('mill/order/notDisable',['id' => '__id__','field'=>'archives_status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->addRightButton('archivesShow',['title' => '面积表详情','href' => url('mill/order/archivesShow',['id' => '__id__']),'data-files'=>'archivesEdit','class'=>'archivesEdit_btn','icon'=>''])
            ->replaceRightButton(['status' => ['in', '1']], '', 'enable,notDisable')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'archives_sn'  => 150,
                'engineering'  => 200,
                'company'  => 200,
                'money_str'  => 60,
                'batch'  => 60,
                'back'  => 60,
                'number_sum'  => 60,
                'area_sum'  => 80,
                'create_time'  => 80,
                'client_time'  => 80,
                'right_button'  => 80,
            ])
            ->fetch(); // 渲染模板
    }
    //获取面积表文档信息并编译
    public function archivesDrawing()
    {

        // 接收附件 ID
        $id = input('param.id');
        // 获取附件 ID 完整路径
        $file = get_file_path($id);
        //$full_path = 'D:/office/phpstudy_pro/WWW/xxy/public/uploads/files/20210611/49dc8272891a2dbdc3396fc055d8017c.xls';
        if(strpos(getcwd(),'public') && strpos($file,'public'))$file = explode('public',$file)[1];
        $full_path = getcwd() . $file;

        $head_table = [
            'sheet'         =>  '面积表',
            'rowStart'      =>  5,
            'rowEnd'        =>  5,
            'table'         =>  'order',
            'fields'        =>  [
                'B-3'       =>  'engineering',
                'B-4'       =>  'archives_open',
                'B-5'       =>  'archives_sn',
                'H-4'       =>  'archives_version',
                'I-4'       =>  'archives_type',
                'K-4'       =>  'archives_handle',
                'M-4'       =>  'archives_bill_time',
                'N-4'       =>  'archives_sign_time',
                'O-4'       =>  'order_sn',
                'P-4'       =>  'batch',
            ]
        ];
        $archives_table = [
            'sheet'         =>  '面积表',
            'rowStart'      =>  7,
            //'rowEnd'        =>  5,
            'table'         =>  'order_archives',
            'fields'        =>  [
                'A'         =>  'sort',
                'B'         =>  'page',
                'C'         =>  'model_sn',
                'D'         =>  'number',
                'E'         =>  'cutting',
                'F'         =>  'size',
                'G'         =>  'one_area',
                'H'         =>  'row_area',
                'I'         =>  'long',
                'J'         =>  'high',
                'K'         =>  'color',
                'L'         =>  'thickness',
                'M'         =>  'model',
                'N'         =>  'slot',
                'O'         =>  'weld',
                'P'         =>  'torque',
            ],
            /*'group'         =>  [
                'fields'    =>  ['thickness','color','model'],
                'sum'       =>  ['number','row_area']
            ]*/
        ];
        $sheet_read_arr = [$head_table,$archives_table];
        $import = plugin_action('Excel/Excel/importarchives', [$full_path,$sheet_read_arr]);

        echo json_encode($import,JSON_UNESCAPED_UNICODE);exit;

    }
    //编辑面积表
    public function archivesEdit($id=null,$isEdit=true)
    {

        if ($this->request->isPost() && $isEdit) {
            $data = $this->request->post();
            //是否为新增面积表，是新增面积表，则自动新增订单
            $is_pid = $data['is_pid'];
            $archives_lists = isset($data['archives_lists'])?$data['archives_lists']:'';
            unset($data['archives_lists']);
            unset($data['is_pid']);
            // 验证
            $result = $this->validate($data, 'Order');
            if(empty($data['archives_drawing']))$this->error('请上传面积表');
            // 验证失败 输出错误信息
            if(true !== $result) $this->error($result);

            $data['give_sort'] = implode(',',$data['give_sort']);

            $data['archives_bill_time'] = strtotime($data['archives_bill_time']);
            $data['archives_sign_time'] = strtotime($data['archives_sign_time']);

            //验证档案号是否唯一
            $isArchives_sn = Db::name('mill_order')->where(['archives_sn'=>$data['archives_sn']])->value('id');

            if($is_pid){
                if($isArchives_sn)$this->error('该档案号已存在');

                unset($data['id']);
                $re = OrderModel::create($data);
                if(!empty($re['id']))$id = $re['id'];
            }
            else {
                if(!empty($isArchives_sn) && $isArchives_sn != $data['id'])$this->error('该档案号已存在');

                $is_speed = Db::name('mill_order_archives_give')->where([['order_id','=',$id],['status','<>',0]])->count();
                //if($is_speed > 0)$this->error('该批次已投入生产,禁止修改');

                $info = Db::name('mill_order')->where(['id'=>$data['id']])->find();
                if(!empty($info['archives_sn']) && $info['archives_sn'] != $data['archives_sn'])$this->error('档案号不匹配');

                $re = OrderModel::update($data);

                //更新发货金额
                FinanceModel::updateAddressPrice($data['id']);

            }
            // 更新数据
            if ($re) {

                //更新面积表
                if(!empty($archives_lists)){

                    //if(empty($archives_lists[0]['sort']))$this->error('请上传序号');
                    //获取所有面积表序列
                    $sort_list = Db::name('mill_order_archives')->where(['order_id'=>$id])->order('sort asc')->column('sort');
                    if(!empty($sort_list))$sort_list = array_flip($sort_list);
                    //获取最后一件产品的序列
                    $sort = Db::name('mill_order_archives_give')
                        ->where(['order_id'=>$id])
                        ->order('sort desc')
                        ->value('sort');

                    foreach ($archives_lists as $av){
                        //过滤未被删减的面积表序列
                        if(!empty($sort_list))unset($sort_list[$av['sort']]);

                        $archives_where = [
                            'order_id'  =>  $id,
                            'sort'  =>  $av['sort'],
                        ];
                        $archives = Db::name('mill_order_archives')->where($archives_where)->find();
                        //录入
                        if(empty($archives)) {
                            $archives['id'] = Db::name('mill_order_archives')->insertGetId($av);
                            $archives = array_merge($archives,$av);
                            //后续新增的面积表序列，且有已被投入生产的产品，则插入新增的产品
                            if($sort){
                                $archives = Db::name('mill_order_archives')->where($archives_where)->find();
                                //获取最后一件产品
                                $give = Db::name('mill_order_archives_give')->where(['order_id'=>$id])->order('sort desc')->find();
                                $count_x = $av['number'];
                                if(!empty($give)){

                                    //获取该序列最后一件产品的序号
                                    $counter_last = Db::name('mill_order_archives_give')->where(['archives_id'=>$archives['id']])->order('sort desc')->value('counter');
                                    $counter_last = intval($counter_last);
                                    for($i=($counter_last+1);$i<=($counter_last+$count_x);$i++){
                                        $counter = $i;//计件数
                                        $sort++;//计件数+1
                                        $add = [
                                            'order_id'              =>  $archives['order_id'],
                                            'order_pid'             =>  $archives['order_pid'],
                                            'archives_id'           =>  $archives['id'],
                                            'archives_sn'           =>  $archives['archives_sn'],
                                            'counter'               =>  $counter,
                                            'give_date'             =>  $give['give_date'],
                                            'batch'                 =>  $give['batch'],
                                            'sort'                  =>  $sort,
                                            'give_sn'               =>  GiveModel::giveSn($give['give_date'],$give['batch'],$sort),
                                        ];

                                        Db::name('mill_order_archives_give')->insert($add);
                                    }
                                }
                            }

                        }
                        //更新
                        else{
                            //有产品增加
                            if($av['number'] > $archives['number']){
                                //获取最后一件产品
                                $give_where = [
                                    'archives_id'   =>  $archives['id'],
                                ];
                                $give = Db::name('mill_order_archives_give')->where($give_where)->order('counter desc')->find();
                                if(empty($give)){
                                    $give = Db::name('mill_order_archives_give')->where(['order_id'=>$id])->order('sort desc')->find();
                                    $archives['number'] = 0;
                                }
                                $count_x = $av['number']-$archives['number'];
                                if(!empty($give)){

                                    //获取该序列最后一件产品的序号
                                    $counter_last = Db::name('mill_order_archives_give')->where(['archives_id'=>$archives['id']])->order('sort desc')->value('counter');
                                    $counter_last = intval($counter_last);
                                    for($i=($counter_last+1);$i<=($counter_last+$count_x);$i++){
                                        $counter = $i;//计件数
                                        $sort++;//计件数+1
                                        $add = [
                                            'order_id'              =>  $archives['order_id'],
                                            'order_pid'             =>  $archives['order_pid'],
                                            'archives_id'           =>  $archives['id'],
                                            'archives_sn'           =>  $archives['archives_sn'],
                                            'counter'               =>  $counter,
                                            'give_date'             =>  $give['give_date'],
                                            'batch'                 =>  $give['batch'],
                                            'sort'                  =>  $sort,
                                            'give_sn'               =>  GiveModel::giveSn($give['give_date'],$give['batch'],$sort),
                                        ];

                                        Db::name('mill_order_archives_give')->insert($add);
                                    }
                                }
                            }
                            //有产品减少
                            elseif($av['number'] < $archives['number']){
                                //获取最初始状态的产品
                                $give_where = [
                                    ['archives_id','=',$archives['id']],
                                    ['quality_status','>=','-1'],
                                ];
                                $count_x = $archives['number']-$av['number'];
                                $give_id = Db::name('mill_order_archives_give')
                                    ->where($give_where)
                                    ->order('status asc,sort desc')
                                    ->limit($count_x)
                                    ->column('id');
                                $give_update_x = ['quality_status'=>'-3'];
                                if(!empty($give_id)){
                                    $give_id = implode(',',$give_id);
                                    Db::name('mill_order_archives_give')->where([['id','in',$give_id]])->update($give_update_x);
                                    Db::name('mill_order_archives_give_log')->where([['give_id','in',$give_id]])->delete();//删除已存在的扫码数据
                                }
                            }
                            //更新
                            Db::name('mill_order_archives')->where(['id'=>$archives['id']])->update($av);
                        }


                        //TODO 同步更新至旧数据库
                        ArchivesModel::checkGive($id,$archives['id']);

                        //更新产品信息
                        Db::name('mill_order_archives_give')->where(['archives_id'=>$archives['id']])->update(['one_area'=>$archives['one_area']]);
                        Db::name('mill_order_archives_give_log')->where(['archives_id'=>$archives['id']])->update(['one_area'=>$archives['one_area']]);
                    }
                    //清除删减的面积表序列
                    if(!empty($sort_list)){
                        $sort_list = array_keys($sort_list);
                        $sort_ids = Db::name('mill_order_archives')->where([['order_id','=',$id],['sort','in',implode(',',$sort_list)]])->order('sort asc')->column('id');
                        if(!empty($sort_ids)){
                            $sort_ids = implode(',',$sort_ids);
                            Db::name('mill_order_archives')->where("id in ({$sort_ids})")->delete();//删除已存在的数据
                            Db::name('mill_order_archives_give')->where("archives_id in ({$sort_ids})")->delete();//删除已存在的数据
                            Db::name('mill_order_archives_give_log')->where("archives_id in ({$sort_ids})")->delete();//删除已存在的数据
                        }
                    }
                    //更新档案号
                    Db::name('mill_order_archives')->where(['order_id'=>$id])->update(['archives_sn'=>$data['archives_sn']]);
                    Db::name('mill_order_archives_give')->where(['order_id'=>$id])->update(['archives_sn'=>$data['archives_sn']]);

                    if($is_pid && cookie('__encry__')){
                        Db::name('mill_order_archives')->where(['encry'=>cookie('__encry__')])->update(['order_id'=>$id,'encry'=>'']);
                        cookie('__encry__','');
                    }

                    //TODO 同步更新至旧数据库
                    Db2Model::archivesEdit($id,$is_pid,$data,$archives_lists,cookie('__encry__'));
                }

                $this->success('编辑成功', cookie('__forward__'));
            } else {
                $this->error('编辑失败');
            }
        }

        $id = input('param.id');
        $order_pid = input('param.order_pid');
        if(empty($id) && empty($order_pid))$this->error('错误操作');
        if (strpos($id, ',') !== false)$this->error('暂不支持批量修改');
        $is_pid = false;
        $encry = '';//加密串
        $title2 = '';
        //工艺选择
        $give_status = GiveModel::$give_status_search;
        unset($give_status[0]);

        // 获取数据
        if($id){
            $info = OrderModel::find($id);
            $archives = Db::name('mill_order_archives')->field('sum(number) as number_sum,sum(row_area) as area_sum')->where(['order_id'=>$id])->find();
            $title2 = "{$info['engineering']}({$info['archives_sn']})({$archives['number_sum']}件)({$archives['area_sum']}m²)";

            if(empty($info['archives_sn'])){
                $info['mill_id'] = 1;
                $info['color_type'] = 1;
                $info['give_sort'] = implode(',',array_keys($give_status));
            }

        }
        elseif ($order_pid){
            $info = OrderModel::where(['order_pid'=>$order_pid])->find();
            $is_pid = true;
            //生成加密串
            $encry = Auth::token();
            cookie('__encry__', $encry);

            unset($info['archives_drawing']);
            unset($info['archives_bill_time']);
            unset($info['archives_sign_time']);
            unset($info['batch']);
            unset($info['archives_handle']);
            unset($info['archives_open']);
            unset($info['archives_plan']);
            unset($info['archives_sn']);
            unset($info['order_sn']);
            unset($info['archives_version']);
            unset($info['archives_type']);
            unset($info['archives_number_sum']);
            unset($info['archives_area_sum']);

            $info['create_time'] = time();
            $info['update_time'] = time();

            $title2 = "{$info['engineering']}";
        }
        $info['is_pid'] = $is_pid;
        $info['archives_bill_time'] = empty($info['archives_bill_time'])?'':$info['archives_bill_time'];
        $info['archives_sign_time'] = empty($info['archives_sign_time'])?'':$info['archives_sign_time'];

        $layui_head = ArchivesModel::$layui_fields;
        foreach ($layui_head as $lhv){
            $table_head[] = $lhv['title'];
        }
        $table_head = [$table_head];
        $table_data = ArchivesModel::getList($id);

        $archives_html_sum = '';
        if($table_data){
            $info['archives_number_sum'] = round(ArchivesModel::where('order_id='.$id)->sum('number'),6);
            $info['archives_area_sum'] = round(ArchivesModel::where('order_id='.$id)->sum('row_area'),6);
            $archives_html_sum = "<div style='text-align: right'>合计数量：<a style='font-size: 25px;'>{$info['archives_number_sum']}</a>  合计面积(M²)：<a style='font-size: 25px;'>{$info['archives_area_sum']}</a></div>";
        }
        $table_thickness_head = [['厚度','合计件数','合计面积',]];
        $table_thickness_data = ArchivesModel::getList($id,'thickness,SUM(number) AS number_sum,SUM(row_area) AS row_area_sum','','thickness');

        $table_model_head = [['板型','合计件数','合计面积',]];
        $table_model_data = ArchivesModel::getList($id,'model,SUM(number) AS number_sum,SUM(row_area) AS row_area_sum','','model');

        $table_color_head = [['颜色','合计件数','合计面积',]];
        $table_color_data = ArchivesModel::getList($id,'color,SUM(number) AS number_sum,SUM(row_area) AS row_area_sum','','color');

        $title = $isEdit?'上传面积表':'面积表详情';
        $hideBtn = $isEdit?'':['submit'];

        //js
        $js = '<script type="text/javascript">
                //上传面积表成功后的回调
                var dp_file_upload_success_archives_drawing = function () {
                    //面积表文档ID
                    var archives_drawing = $("input[name=archives_drawing]").val();
                    //获取面积表文档信息并编译
                    $.ajax({
                        url: \''.url("archivesDrawing").'?id=\'+archives_drawing,
                        type: \'GET\'
                    }).done(function(data) {
                        data = $.parseJSON(data);
                        
                        //更新订单信息
                        var order = [];
                        if(data.order.lists[0]){
                            order = data.order.lists[0];
                            $("input[name=engineering]").val(order.engineering);
                            $("input[name=order_sn]").val(order.order_sn);
                            $("input[name=archives_version]").val(order.archives_version);
                            $("input[name=archives_type]").val(order.archives_type);
                            $("input[name=archives_sn]").val(order.archives_sn);
                            $("input[name=archives_sign_time]").val(order.archives_sign_time);
                            $("input[name=archives_bill_time]").val(order.archives_bill_time);
                            $("input[name=archives_handle]").val(order.archives_handle);
                            $("input[name=archives_open]").val(order.archives_open);
                            $("input[name=batch]").val(order.batch);
                            
                        }
                        
                        //更新面积表信息
                        var archives_html = "";
                        var group_thickness_obj = {};
                        var group_model_obj = {};
                        var group_color_obj = {};
                        if(data.order_archives.lists){
                            var lists = data.order_archives.lists;
                            
                            var number_sum = 0;
                            var row_area_sum = 0;
                            $.each(lists,function(i,v){
                                var k = v["sort"];
                                if(k == ""||k == "null"){
                                    Dolphin.notify("序号不能为空", "danger");
                                }
                                v["row_area"] = Math.round((v["number"]*v["one_area"])*1000000)/1000000;
                                archives_html += "<tr><input type=\'hidden\' name=\'archives_lists["+k+"][order_id]\' value=\''.$id.'\'><input type=\'hidden\' name=\'archives_lists["+k+"][order_pid]\' value=\''.$info['order_pid'].'\'><input type=\'hidden\' name=\'archives_lists["+k+"][encry]\' value=\''.$encry.'\'><input type=\'hidden\' name=\'archives_lists["+k+"][slot]\' value=\'"+v["slot"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][weld]\' value=\'"+v["weld"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][torque]\' value=\'"+v["torque"]+"\'><input type=\'hidden\' name=\'archives_lists["+k+"][archives_sn]\' value=\'"+order.archives_sn+"\'>"
                                +"<td>"+v["sort"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][sort]\' value=\'"+v["sort"]+"\'></td>"
                                +"<td>"+v["page"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][page]\' value=\'"+v["page"]+"\'></td>"
                                +"<td>"+v["model_sn"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][model_sn]\' value=\'"+v["model_sn"]+"\'></td>"
                                +"<td>"+v["number"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][number]\' value=\'"+v["number"]+"\'></td>"
                                +"<td>"+v["cutting"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][cutting]\' value=\'"+v["cutting"]+"\'></td>"
                                +"<td>"+v["size"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][size]\' value=\'"+v["size"]+"\'></td>"
                                +"<td>"+v["one_area"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][one_area]\' value=\'"+v["one_area"]+"\'></td>"
                                +"<td>"+v["row_area"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][row_area]\' value=\'"+v["row_area"]+"\'></td>"
                                +"<td>"+v["long"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][long]\' value=\'"+v["long"]+"\'></td>"
                                +"<td>"+v["high"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][high]\' value=\'"+v["high"]+"\'></td>"
                                +"<td>"+v["color"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][color]\' value=\'"+v["color"]+"\'></td>"
                                +"<td>"+v["thickness"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][thickness]\' value=\'"+v["thickness"]+"\'></td>"
                                +"<td>"+v["model"]+"<input type=\'hidden\' name=\'archives_lists["+k+"][model]\' value=\'"+v["model"]+"\'></td>"
                                +"</tr>";
                                
                                //统计
                                number_sum += parseFloat(v["number"]);
                                row_area_sum += parseFloat(v["row_area"]);
                                
                                //厚度统计
                                var thickness_field = v["thickness"];
                                if(!group_thickness_obj.hasOwnProperty(thickness_field))group_thickness_obj[thickness_field] = {"number_sum":0,"row_area_sum":0};
                                group_thickness_obj[thickness_field]["number_sum"] += parseFloat(v["number"]);
                                group_thickness_obj[thickness_field]["row_area_sum"] += parseFloat(v["row_area"]);
                                
                                //板型统计
                                var model_field = v["model"];
                                if(!group_model_obj.hasOwnProperty(model_field))group_model_obj[model_field] = {"number_sum":0,"row_area_sum":0};
                                group_model_obj[model_field]["number_sum"] += parseFloat(v["number"]);
                                group_model_obj[model_field]["row_area_sum"] += parseFloat(v["row_area"]);
                                
                                //颜色统计
                                var color_field = v["color"];
                                if(!group_color_obj.hasOwnProperty(color_field))group_color_obj[color_field] = {"number_sum":0,"row_area_sum":0};
                                group_color_obj[color_field]["number_sum"] += parseFloat(v["number"]);
                                group_color_obj[color_field]["row_area_sum"] += parseFloat(v["row_area"]);
                            });
                            
                            //组装
                            $("input[name=archives_number_sum]").val(number_sum);
                            $("input[name=archives_area_sum]").val(Math.round(row_area_sum*1000000)/1000000);
                            var archives_html_sum = "<tr><td colspan=\\"13\\" style=\\"text-align: right;\\">合计数量：<a style=\\"font-size: 25px;\\">"+number_sum+"</a>  合计面积(M²)：<a style=\\"font-size: 25px;\\">"+Math.round(row_area_sum*1000000)/1000000+"</a></td></tr>";
                            $("#table-list_archives").find("tbody").html("");
                            
                            //标题
                            var title = order.engineering+"("+order.archives_sn+")"+"("+number_sum+"件)"+"("+Math.round(row_area_sum*1000000)/1000000+"m²)";
                            $("#form_group_ititle2 .ititle").html(title);
                            
                            form_table_tbody(archives_html);
                            
                            // 显示合计结果
                            $(".layui-table-box").append("<div class=\\"layui-table-foot\\" style=\\"text-align: right;\\">"+archives_html_sum+"</div>");
                        }
                        
                        //更新统计信息
                        var group_html = "";
                        if(group_thickness_obj){
                            group_html = "";
                            $.each(group_thickness_obj,function(ck,cv){
                                group_html += "<tr>"
                                +"<td>"+ck+"</td>"
                                +"<td>"+cv["number_sum"]+"</td>"
                                +"<td>"+(Math.round(cv["row_area_sum"]*1000000)/1000000)+"</td>"
                                +"</tr>";

                            });
                            $("#table-list_archives_thickness").find("tbody").html(group_html);
                        }
                        if(group_model_obj){
                            group_html = "";
                            $.each(group_model_obj,function(ck,cv){
                                group_html += "<tr>"
                                +"<td>"+ck+"</td>"
                                +"<td>"+cv["number_sum"]+"</td>"
                                +"<td>"+(Math.round(cv["row_area_sum"]*1000000)/1000000)+"</td>"
                                +"</tr>";
                                
                            });
                            $("#table-list_archives_model").find("tbody").html(group_html);
                        }
                        if(group_color_obj){
                            group_html = "";
                            $.each(group_color_obj,function(ck,cv){
                                group_html += "<tr>"
                                +"<td>"+ck+"</td>"
                                +"<td>"+cv["number_sum"]+"</td>"
                                +"<td>"+(Math.round(cv["row_area_sum"]*1000000)/1000000)+"</td>"
                                +"</tr>";

                            });
                            $("#table-list_archives_color").find("tbody").html(group_html);
                        }
                        
                        
                    });
                };
        
                $(function(){
                    $("#picker_archives_drawing .webuploader-pick").html("上传面积表");
                    
                    // 显示合计结果
                    $(".layui-table-box").append("<div class=\\"layui-table-foot\\" style=\\"text-align: right;\\">'.$archives_html_sum.'</div>");
                    
                    //底部按钮居中
                    $(".dch-form-btn").css("width",$(".row").width());
                    $(window).resize(function() {
                        $(".dch-form-btn").css("width",$(".row").width());
                    });
                })
            </script>';
        //css
        $css = "<style>
                .block-title {
                    display: none;
                }
                .block-options li:first-child {
                    background-color: #E3E9EE;
                    margin-top: -10px;
                }
                .layui-table-box {
                    display: inline-block;
                    border-top: 1px solid #ddd;
                    margin-left: -2px;
                }
                .dch-form-table {
                    text-align: center;
                    margin-top: 50px;
                }
                .dch-form-table label {
                    font-weight: bold;
                    background-color: #c4c6c6;
                }
                .dch-form-table > .table-bordered>tbody>tr>td, .table-bordered>tbody>tr>th, .table-bordered>tfoot>tr>td, .table-bordered>tfoot>tr>th, .table-bordered>thead>tr>td, .table-bordered>thead>tr>th {
                    text-align: center;
                    font-weight: bold;
                    background-color: #c4c6c6;
                }
                .table>thead:first-child>tr:first-child>th,.layui-table-view .layui-table th {
                    background-color: #c4c6c6;
                    padding: unset;
                    height: 28px;
                }
                .dch-form-btn {
                    text-align: center;
                    position: fixed;
                    left: 0px;
                    top: 880px;
                    max-width: 1920px;
                }
                #form_group_list_archives {
                    margin-top: auto;
                }
                .row {
                    padding-bottom: 50px;
                }
                .layui-btn-primary {
                    background-color: #d9534f;
                    color: #fff;
                }
            </style>";

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->addFormItem('hidden', 'id')
            ->addFormItem('hidden', 'order_pid')
            ->addFormItem('hidden', 'is_pid')
            ->addFormItem('hidden', 'client_id')
            ->addFormItem('hidden', 'sales_id')
            ->addFormItem('hidden', 'back')
            ->addFormItem('hidden', 'money_str')
            ->addFormItem('hidden', 'contract')
            ->addFormItem('hidden', 'archives_plan')
            ->addFormItem('hidden', 'archives_type')
            ->addFormItem('hidden', 'create_time')
            ->addFormItem('hidden', 'update_time')
            ->addFormItem('hidden', 'archives_number_sum')
            ->addFormItem('hidden', 'archives_area_sum')
            ->addFormItems([ // 批量添加表单项
                ['ititle:4', 'ititle1', $title,'','','','text-danger'],
                ['ititle:3', 'ititle2', $title2],
                ['file:5', 'archives_drawing', ''],
                ['radio:2', 'color_type', '工艺喷涂','',OrderModel::$color_type,1],
                ['radio:3', 'type', '订单类型','',OrderModel::$types,0],
                ['radio:3', 'mill_id', '车间选择','',ClientModel::getMillList(),1],
                ['checkbox:4', 'give_sort', '工艺选择','',$give_status],
                ['ititle:12', 'ititle3', '编辑'],
                ['text:3', 'engineering', '工程名称'],
                ['text:3', 'archives_sn', '档案号'],
                ['text:2', 'batch', '下单批次'],
                ['select:2', 'sales_id', '业务经理','',ClientModel::getStaffList(1)],
                ['text:2', 'back', '内勤人员'],
                ['text:3', 'archives_open', '面积计算'],
                ['text:3', 'archives_version', '计算版本'],
                ['text:2', 'order_sn', '订单编号'],
                ['date:2', 'archives_sign_time', '签字日期'],
                ['date:2', 'archives_bill_time', '发单日期'],
                ['text:12', 'note', '备注'],
                ['complexTable2:12', 'list_archives', '面积表', $table_data, $table_head,$layui_head,'dch-form-table'],
                ['complexTable:4', 'list_archives_thickness', '面积表统计（厚度）', $table_thickness_data, $table_thickness_head,'','dch-form-table'],
                ['complexTable:4', 'list_archives_model', '面积表统计（版型）', $table_model_data, $table_model_head,'','dch-form-table'],
                ['complexTable:4', 'list_archives_color', '面积表统计（颜色）', $table_color_data, $table_color_head,'','dch-form-table'],
            ])
            ->setFormData($info)
            ->setExtraJs($js)
            ->setExtraCss($css)
            ->hideBtn($hideBtn)
            ->fetch();
    }
    //删除整个面积表信息
    public function delArchives(){

        $order_id = input('order_id');

        $give_count = Db::name('mill_order_archives_give')->where([['order_id','=',$order_id],['status','>',0]])->find();
        if(!empty($give_count)){
            Db::name('mill_order')->where(['id'=>$order_id])->update(['archives_del_status'=>0]);
            $this->error('该工程已开始生产');
        }
        Db::name('mill_order')->where(['id'=>$order_id])->update(['archives_status'=>'','archives_del_status'=>0,'archives_drawing'=>0]);
        Db::name('mill_order_archives')->where(['order_id'=>$order_id])->delete();
        Db::name('mill_order_archives_extra')->where(['order_id'=>$order_id])->delete();
        Db::name('mill_order_archives_give')->where(['order_id'=>$order_id])->delete();
        Db::name('mill_order_archives_give_log')->where(['order_id'=>$order_id])->delete();
        Db::name('mill_order_archives_initial_price')->where(['order_id'=>$order_id])->delete();

        $this->success('删除成功');

    }

    //--------------------------------------发货管理---------------------------------------------------
    //发货管理首页
    public function deliverIndex($REQUEST_URI = true){
        if(empty($REQUEST_URI))cookie('__forward__', $_SERVER['REQUEST_URI']);

        $option = "{
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
            
                        },
                        grid: {
                            left: '50',
                            right: '50',
                            bottom: '0',
                            top:'30',
                            containLabel: true
                        },
                        calculable : true,
                        xAxis: {
                            type: 'category',
                            boundaryGap : false,
                            data: data.head
                        },
                        yAxis : [
                            {
                                type : 'value',
                                axisLabel : {
                                    show: true  // 取消纵坐标的标线
                                },
                                axisLine: {
                                    show: true  // 取消纵坐标的标线
                                },
                                axisTick: {
                                    show: true  // 取消纵坐标的标线
                                },
                                splitLine: {
                                    show: true  // 取消纵坐标的标线
                                }
                            }
                        ],
                        series: data.series
                    }";
        $url = url('mill/stat/ajaxAddress');
        $top_html = StatModel::topStatHtml($url,$option,['year','charts']);

        //额外HTML代码
        //$extra_html = StatModel::addressToGiveShowHtml();
        $extra_html = '';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('') // 页面标题
            ->setTableName('mill_client') // 设置表名
            ->setExtraHtml($top_html.$extra_html,'block_top')
            ->setExtraHtml($extra_html)
            ->fetch(); // 渲染模板
    }
    //发货中首页
    public function deliverIngIndex(){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        return $this->deliverIndex(false);
    }
    //发货列表页
    public function deliver($address_status = '0,1,2',$_show_i = '',$title='发货记录')
    {
        //cookie('__forward__', $_SERVER['REQUEST_URI']);

        //定时任务，超过24小时未确认发货，则自动发货
        //GiveModel::taskSubGiveAddress();

        // 获取查询条件
        $map = $this->getMap();
        if(!empty($map)){
            foreach ($map as $k=>$v){
                if($v[0] == 'client_id'){
                    if(!empty($v[2])){
                        $order_ids = Db::name('mill_order')->where(['client_id'=>$v[2]])->column('id');
                        if(!empty($order_ids)){
                            $order_ids = implode(',',$order_ids);
                            unset($map[$k]);
                            $map[] = ['g.order_id','in',$order_ids];
                        }
                    }

                }
            }
        }
        sort($map);

        // 数据列表
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("g.order_id,g.car_id,g.status".GiveModel::$last_give_status."_time,g.address_time,g.address_date,g.address_sn,g.address_status")
            ->where($map)
            ->where("g.address_sn != '' and g.address_status in ({$address_status})")
            ->group("g.address_sn")
            ->order("g.address_status asc,g.address_date desc,g.status".GiveModel::$last_give_status."_time desc")
            ->paginate()
            ->each(function ($v){
                $order = Db::name('mill_order')->where(['id'=>$v['order_id']])->find();
                $v = array_merge($order,$v);

                $v['id'] = $v['address_sn'];

                $v['plate_number'] = Db::name('mill_car')->where(['id'=>$v['car_id']])->value('plate_number');

                $status_arr = ['0'=>'装车中','1'=>'待打印','2'=>'装车完成'];
                $v['address_status_str'] = OrderModel::status_tag($v['address_status'],$status_arr[$v['address_status']]);

                return $v;
            })
        ;

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order') // 设置表名
            //->setSearch(['o.engineering' => '工程名称', 'o.archives_sn' => '档案号', 'c.company' => '客户名称', 'o.back' => '内勤']) // 设置搜索参数
            ->setSearchArea([
                ['select:1', 'g.car_id', '车牌号码','','',CarModel::getList()],
                ['select:2', 'client_id', '客户公司','','',ClientModel::getList('company')],
                ['select:2', 'g.order_id', '工程名称','','',OrderModel::getList()],
                ['text:2', 'g.archives_sn', '档案号', 'like'],
            ])
            //->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['address_sn', '发货单号','jump_right','','address_sn=__address_sn__'],
                ['plate_number', '车牌号码'],
                ['engineering', '工程名称'],
                ['archives_sn', '档案号'],
                ["status".GiveModel::$last_give_status."_time", '发货开始','datetime'],
                ['address_time', '发货结束','datetime'],
                ['address_status_str','发货状态'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('deliverMerge',['title' => '合并发货单','href' => url('deliverMerge'),'class'=>'btn btn-default js-get','target-form'=>'address_sns','float'=>'right'])
            ->addTopButton('print',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print'])

            ->addRightButton('deliverSub',['title' => '确认装车','href' => url('deliverSub',['address_sn'=>'__address_sn__']),'icon'=>'','class'=>'btn btn-primary disable-dch ajax-get confirm'])
            ->addRightButton('deliverGiveIndex',['title' => '补货','href' => url('deliverGiveIndex',['address_sn'=>'__address_sn__']),'float'=>'right'],false)

            ->replaceRightButton(['address_status' => ['=','0']],'',['deliverGiveIndex'])
            ->replaceRightButton(['address_status' => ['<>','0']],'',['deliverSub'])
            ->setRowList($data_list) // 设置表格数据
            ->setWidth('45%') // 设置表格宽度
            ->setColumnWidth([
                'id'  => 60,
                'archives_sn'  => 100,
                'engineering'  => 150,
                'address_status'  => 65,
                'address_time'  => 110,
                "status".GiveModel::$last_give_status."_time"  => 110,
                'right_button'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    //发货中列表页
    public function deliverIng()
    {
        $address_status = '0,1';
        return $this->deliver($address_status,'2','发货单');
    }
    //发货详情
    public function deliverShow()
    {
        $config = new ConfigModel();
        //备注
        $deliver_note = $config->getConfig('mill_deliver_note');

        $address_sn = input('address_sn');//指定发货单号
        if(empty($address_sn))$this->error('错误操作');
        //打印 1:打印 2:导出
        $print = input('print');

        if ($this->request->isPost()) {
            $data = $this->request->post();
            $id = $data['id'];
            unset($data['print']);
            unset($data['id']);

            //更新发货产品信息
            Db::name('mill_order_archives_give')->where(['address_sn'=>$data['address_sn']])->update(['address_status'=>2]);
            //更新发货单其他信息
            if(!empty($id))Db::name('mill_order_archives_address')->where('id='.$id)->update($data);
            else Db::name('mill_order_archives_address')->insert($data);
            //更新发货金额
            FinanceModel::updateAddressPrice($data['order_ids'],$data['address_sn']);

            //更新备注
            ConfigModel::where('name', 'mill_deliver_note')->update(['value' => $deliver_note]);
            //数据存储成功，并配置打印模板，进行打印
            $this->success('操作成功', admin_url('mill/order/delivershow',['address_sn'=>$address_sn,'print'=>$print]),'_blank');

            $this->error('操作失败');
        }

        $where[] = ['g.address_sn','=',$address_sn];

        $archives_fields = [];
        foreach (ArchivesModel::$layui_fields as $lhv){
            if($lhv['field'] == 'number')$archives_fields["COUNT(g.id) as number"] = $lhv['title'];
            elseif($lhv['field'] == 'row_area')$archives_fields["(COUNT(g.id)*FORMAT(a.one_area,6)) as row_area"] = $lhv['title'];
            else $archives_fields["a.{$lhv['field']}"] = $lhv['title'];
        }
        $archives_fields['FROM_UNIXTIME(o.archives_bill_time,\'%Y-%m-%d\') as archives_bill_time'] = '来单日期';

        $archives_field = implode(',',array_keys($archives_fields)).",(COUNT(g.id)*a.slot) as slot,(COUNT(g.id)*a.weld) as weld,(COUNT(g.id)*a.torque) as torque,g.order_id";

        $archives_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field($archives_field)
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where($where)
            ->group('a.id')
            ->order('a.sort asc')
            ->select();

        $order = Db::name('mill_order')
            ->alias('o')
            ->field('o.*,ms.staff as sales,c.company,c.mobile as c_mobile,0 as number_sum,0 as area_sum,0 as slot,0 as weld,0 as torque')
            ->leftJoin('mill_staff ms','o.sales_id=ms.id','left')
            ->leftJoin('mill_client c','c.id=o.client_id','left')
            ->where(['o.id'=>$archives_list[0]['order_id']])
            ->find();

        foreach ($archives_list as &$v){
            $order['slot'] += $v['slot'];
            $order['weld'] += $v['weld'];
            $order['torque'] += $v['torque'];
            $order['number_sum'] += $v['number'];
            $order['area_sum'] += $v['row_area'];

            unset($v['slot']);
            unset($v['weld']);
            unset($v['torque']);
            unset($v['order_id']);
        }

        //面积表信息
        $order['table_archives']['head'] = array_values($archives_fields);
        $order['table_archives']['data'] = $archives_list;

        //表头
        $order['table_head'][] = [
            "[5:1]<div class='dch-'>客户名称:{$order['company']}</div>",
            "[5:1]<div class='dch-'>工程名称:{$order['engineering']}</div>",
            "[4:1]<div class='dch-'>批次:{$order['batch']}</div>",
        ];
        $order['table_head'][] = [
            "[5:1]<div class='dch-'>档案编号:{$order['archives_sn']}</div>",
            "[5:1]<div class='dch-'>业务经理:{$order['sales']}</div>",
            "[4:1]<div class='dch-'>发货单号:{$address_sn}</div>",
        ];

        $title = "打印送货清单";

        //基本计价
        $order['table_archives_group']['head'] = ['厚度','颜色','铝板版型','合计数量(件)','合计面积(M²)','单价(元)','合计金额(元)'];

        $join = [['mill_order_archives_give g','a.id=g.archives_id','left'],['mill_order o','a.order_id=o.id','left']];
        $table_group_field = "a.thickness,a.color,a.model,SUM(g.number) AS number_sum,ROUND(SUM(a.one_area),4) AS one_area_sum,group_concat(a.id) as archives_ids,a.order_id";
        $order['table_archives_group']['data'] = ArchivesModel::getList('',$table_group_field,'','a.thickness,a.color,a.model',$join,$where);

        //获取最后一个发货人信息
        $last_give = Db::name('mill_order_archives_give_log')->field('*')->where([['address_sn','=',$address_sn]])->order('status_time desc')->find();
        $last_give2 = Db::name('mill_order_archives_give_log')->field('GROUP_CONCAT(DISTINCT order_id) as order_ids,GROUP_CONCAT(DISTINCT archives_sn) as archives_sns')->where([['address_sn','=',$address_sn]])->find();
        $last_give = array_merge($last_give,$last_give2);
        $user = Db::name('mill_staff')->field('staff as nickname,staff_mobile as mobile')->where('id='.$last_give['status_uid'])->find();
        //发货单信息
        $address = Db::name('mill_order_archives_address')->where(['address_sn'=>$address_sn])->find();
        if(empty($address)){
            $address['id'] = '';
            $address['address_sn'] = $address_sn;
            $address['user_nickname'] = $user['nickname'];
            $address['user_mobile'] = $user['mobile'];
            $address['address_date'] = $last_give['address_date'];
            $address['car_nickname'] = '';
            $address['car_mobile'] = '';
            $address['create_time'] = time();
            $address['note'] = $deliver_note;

        }
        $address['order_pid'] = $last_give['order_pid'];
        $address['order_ids'] = $last_give['order_ids'];
        $address['archives_sns'] = $last_give['archives_sns'];

        $order['address'] = $address;

        $table_arr = AddressModel::fromTabale($order);
        $table_head = $table_arr['head'];
        $table_data = $table_arr['data'];
        $js = $table_arr['js'];
        $css = $table_arr['css'];

        //print 1:打印模式 2:导出模式
        if($print){
            echo AddressModel::toHtml($order,$print);exit;
        }

        $left_data = ['title'=>'发货单','url'=>url('mill/order/deliverShow'),'param'=>'address_sn','back_url'=>cookie('__forward__')];
        $top_html = StatModel::ajaxLeftHtml($left_data,url('mill/stat/ajaxAddressList'));

        return ZBuilder::make('form')
            ->setPageTitle($title) // 页面标题
            ->setExtraHtml($top_html,'content_top')
            ->addFormItems([ // 批量添加表单项
                ['hidden','print',1],
                ['complexTable:12', 'list_archives_group', '', $table_data, $table_head],
            ])
            ->setExtraCss($css)
            ->setExtraJs($js)
            ->setBtnTitle(['submit' => '提交打印'])
            ->fetch();

    }
    //产品明细发货进度首页
    public function deliverGiveIndex(){
        $option = "{
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            }
                        },
                        legend: {
            
                        },
                        grid: {
                            left: '50',
                            right: '50',
                            bottom: '0',
                            top:'30',
                            containLabel: true
                        },
                        calculable : true,
                        xAxis: {
                            type: 'category',
                            boundaryGap : false,
                            data: data.head
                        },
                        yAxis : [
                            {
                                type : 'value',
                                axisLabel : {
                                    show: true  // 取消纵坐标的标线
                                },
                                axisLine: {
                                    show: true  // 取消纵坐标的标线
                                },
                                axisTick: {
                                    show: true  // 取消纵坐标的标线
                                },
                                splitLine: {
                                    show: true  // 取消纵坐标的标线
                                }
                            }
                        ],
                        series: data.series
                    }";
        $url = url('mill/stat/ajaxAddress');
        $top_html = StatModel::topStatHtml($url,$option,['year','charts']);

        session('_deliverGiveIndex_address_sn',input('address_sn'));

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('') // 页面标题
            ->setTableName('mill_client') // 设置表名
            ->setExtraHtml($top_html,'block_top')
            ->fetch(); // 渲染模板
    }
    //产品明细发货进度
    public function deliverGiveShow($index = false,$not_address = 0,$address_sn = '',$url = '')
    {
        //cookie('__forward__', $_SERVER['REQUEST_URI']);

        //发货状态
        $give_status = GiveModel::$last_give_status;
        $not_address = input('not_address',$not_address);//0:已发货 1:未发货
        $address_sn = input('address_sn',$address_sn);
        if(empty($url))$url = url('deliverGiveShow');

        if(!empty($address_sn)){
            $order_ids = Db::name('mill_order_archives_give')->where(['address_sn'=>$address_sn])->group('order_id')->column('order_id');
            $order_ids = implode(',',$order_ids);
        }
        else $order_ids = '';

        $status_title = '已';
        if($index && $not_address == 1)$status_title = '未';
        $title = "{$status_title}发货列表";
        $group_name = "&nbsp;&nbsp;&nbsp;&nbsp;{$status_title}发货产品列表";
        $data_list = [];
        if(!empty(input()) || $address_sn){
            // 获取查询条件
            $map = $this->getMap();

            if(!empty($map)){
                foreach ($map as $m){
                    if($m[0] == 'g.archives_sn')$archives_sn = trim($m[2],'%');
                }
            }

            if($not_address == 1) {
                $map[] = ['g.status','<',$give_status];
                $map[] = ['g.order_id','in',$order_ids];
            }
            else $map[] = ['g.address_sn','=',$address_sn];

            //统计
            $data_stat = Db::name('mill_order')->field('engineering,archives_sn')->where([['id','in',$order_ids]])->find();
            $data_stat['order_ids'] = $order_ids;
            $data_stat['address_sn'] = $address_sn;
            $data_stat['address_number'] = 0;
            $data_stat['address_area'] = 0;

            // 数据列表
            $data_list = Db::name('mill_order_archives_give')
                ->alias('g')
                ->field("g.*,o.batch,a.model,a.model_sn,a.thickness,a.one_area,a.color,a.page,a.long,a.high,a.sort as a_sort")
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->leftJoin('mill_order o','o.id=g.order_id')
                ->where($map)
                ->order('g.id')
                ->select();

            if(!empty($data_list)){
                foreach ($data_list as &$v){

                    //序号
                    $v['a_sort'] = "{$v['a_sort']}-{$v['counter']}";

                    //二维码
                    $v['give_sn_code'] = '<div class="js-gallery"><img class="layui-img" style="width: 20px" src="'.plugin_url('Qrcode/Qrcode/generate', ['text' => $v['give_sn']]).'" /></div>';

                    //状态
                    $str = '';
                    $str .= '<span class="label label-primary">'.GiveModel::$give_status[$v['status']];
                    if($v['quality_status']<0)$str .= GiveModel::$quality_status[$v['quality_status']];
                    $str .= '</span>';
                    $v['status'] = $str;

                    $data_stat['address_number'] ++;
                    $data_stat['address_area'] += $v['one_area'];
                }
            }

            $data_stat_sum = ArchivesModel::getOneStat($order_ids,'order_id','in',[],[],$give_status);
            $data_stat = array_merge($data_stat,$data_stat_sum);
            $data_stat['status_area_no_sum'] = floatval($data_stat['status_area_no_sum']);
            $data_stat['status_no_sum'] = floatval($data_stat['status_no_sum']);

            $title = "({$data_stat['engineering']})({$data_stat['archives_sn']})({$data_stat['address_sn']})".$title;
            $group_name = "&nbsp;&nbsp;&nbsp;&nbsp;{$status_title}发货产品列表<font color='#5FB878'>(数量:{$data_stat['address_number']} 面积:{$data_stat['address_area']})</font>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;未发货<font color='#337ab7'>【面积:{$data_stat['status_area_no_sum']} 总数量:{$data_stat['status_no_sum']}】</font>";

            if(!$index){
                $topButton = [
                    'deliverGiveIndex'      =>  [['title' => '补货卸货','href' => url('deliverGiveIndex',['address_sn'=>$address_sn]),'class'=>'btn btn-danger','float'=>'right'],false],
                    //'ableGive'              =>  [['title' => '卸货','href' => url('ableGive',['address_sn'=>$address_sn,'type'=>1]),'icon'=>'','class'=>'btn btn-danger','float'=>'right'],['area' => ['780px', '45%'], 'title' => ['卸货', 'font-size:24px;text-align: center;']]],
                    //'ableGive2'             =>  [['title' => '批量卸货','href' => url('ableGive',['address_sn'=>$address_sn,'type'=>1]),'icon'=>'','class'=>'btn btn-danger ajax-post confirm','target-form'=>'ids','float'=>'right'],false],
                    'deliverShow'           =>  [['title' => '打印发货单','href' => url('deliverShow',['address_sn' =>$address_sn]),'class'=>'btn btn-primary disable-dch','float'=>'right'],false],
                ];
            }
            else{
                if($not_address == 1)$group_name = "&nbsp;&nbsp;&nbsp;&nbsp;{$status_title}发货产品列表 <font color='#337ab7'>【数量:{$data_stat['address_number']} 面积:{$data_stat['address_area']}】</font>";
                else $group_name = "&nbsp;&nbsp;&nbsp;&nbsp;{$status_title}发货产品列表<font color='#5FB878'>【数量:{$data_stat['address_number']} 面积:{$data_stat['address_area']}】</font>";
            }

        }

        $topButton['print'] = [['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print','float'=>'right','lay-event'=>'quality-print']];

        $width = $index?'88%':'-webkit-fill-available';
        $index_js = '';
        if($index && $not_address == 0){
            $index_js = '
                    //插入左右按钮表单
                    var html = "<div class=\"layui-btn-group\">"+
                                "<button type=\"button\" class=\"layui-btn arrow-btn\" id=\"left-arrow\" target-form=\"ids\" data-url=\"'.url('ableGive',['address_sn'=>$address_sn]).'\">"+
                                "   <i class=\"layui-icon layui-icon-prev\"></i>"+
                                "</button>"+
                                "<button type=\"button\" class=\"layui-btn arrow-btn\" id=\"right-arrow\" target-form=\"ids\" data-url=\"'.url('ableGive',['address_sn'=>$address_sn,'type'=>1]).'\">"+
                                "   <i class=\"layui-icon layui-icon-next\"></i>"+
                                "</button>"+
                                "<form name=\"ids\"><input class=\"arrow-ids\" type=\"hidden\" name=\"ids\" value=\"\"><a style=\"divplay:none\" class=\"ajax-post confirm\" id=\"arrow-sub\" target-form=\"ids\" data-url=\"\"></a></form>"+
                                "</div>";
                                
                    if(!$(".arrow-btn").length)giveshow_obj.after(html);
                    
                    //左右按钮点击事件
                    $(".arrow-btn").unbind("click");
                    $(".arrow-btn").click(function(){
                    
                        var id = $(this).attr("id");
                        if(id == "right-arrow")id = 0;
                        else id = 1;
                        var obj = $(".table-list").eq(id);
                        var form = $(obj).find("input[name=layTableCheckbox][type=checkbox]:checked").parents("td[data-field=\'_primary_key_value\']");
                        var ids = [];
                        form.each(function () {
                            ids.push($(this).data("content"));
                        });
                        ids = ids.join(",");
                        
                        if(!ids){
                            Dolphin.notify("请选择要操作的数据", "warning");
                            return false;
                        }
                        $(".arrow-ids").val(ids);
                        $("#arrow-sub").attr("data-url",$(this).attr("data-url"));
                        $("#arrow-sub").click();
                    });
                ';
        }
        //JS
        $js = '<script type="text/javascript">
                layui_func["deliverGiveShow"] = function (){
                    var giveshow_url = \''.$url.'\';
                    var giveshow_obj = $("form[action=\'"+giveshow_url+"\']").parents(".table-list");
                        
                    giveshow_obj.find(".laytable-cell-group").attr("align","left");
                    
                    '.$index_js.'
                    
                };
            </script>';
        //CSS
        $css = '<style>
                    .layui-btn-group{padding-top: 13%;margin-left: 4px;margin-right: 2px;}
                    .arrow-btn{background-color: #009933;color: #fff;padding: unset;margin-bottom: 30px;}
                    .layui-btn-group .layui-btn:first-child {border-radius: 4px;}
                    .layui-btn-group .layui-btn {border-radius: 4px;}
                </style>';

        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            //->hideCheckbox()
            ->setSearchArea([
                ['text:2', 'give_sn', '条码编号', 'like'],
            ])
            ->addColumns([ // 批量添加列
                ['batch', '批次','','','','',['group'=>$group_name]],
                ['a_sort','序号','','','','',['group'=>$group_name]],
                ['page', '图纸页码','','','','',['group'=>$group_name]],
                ['long', 'L(M²)','','','','',['group'=>$group_name]],
                ['high', 'H(M²)','','','','',['group'=>$group_name]],
                ['model_sn', '铝板编号','','','','',['group'=>$group_name]],
                ['thickness', '板厚(MM)','','','','',['group'=>$group_name]],
                ['model', '版型','','','','',['group'=>$group_name]],
                ['one_area', '面积(M²)','','','','',['group'=>$group_name]],
                ['status','发货状态','','','','',['group'=>$group_name]],
                ['give_sn', '二维码编号','','','','',['group'=>$group_name]],
                ['give_sn_code', '二维码','','','','',['group'=>$group_name]],
                ['price', '加价部分','','','','',['group'=>$group_name]],
            ])
            ->setExtraJs($js)
            ->setExtraCss($css)
            ->addTopButtons($topButton)
            ->setRowList($data_list) // 设置表格数据
            ->setWidth($width) // 设置表格宽度
            ->setColumnWidth([
                'batch'  => 60,
                'a_sort'  => 60,
                'thickness'  => 50,
                'one_area'  => 80,
                'page'  => 60,
                'long'  => 40,
                'high'  => 40,
                'give_sn'  => 110,
                'give_sn_code'  => 40,
                'price'  => 50,
            ])
            ->noPages()
            ->fetch(); // 渲染模板
    }
    //产品明细发货进度 已发
    public function deliverGiveShowYes()
    {
        return $this->deliverGiveShow(true,0,session('_deliverGiveIndex_address_sn'),url('deliverGiveShowYes'));
    }
    //产品明细发货进度 未发
    public function deliverGiveShowNo()
    {
        return $this->deliverGiveShow(true,1,session('_deliverGiveIndex_address_sn'),url('deliverGiveShowNo'));
    }
    //确认装车
    public function deliverSub()
    {
        //发货单号
        $address_sn = input('address_sn');
        if(empty($address_sn))$this->error("请选择发货单号");
        //同产品的信息
        $address_give = Db::name('mill_order_archives_give')
            ->where(['address_sn'=>$address_sn])
            ->find();
        //未装车
        $address_give0 = Db::name('mill_order_archives_give')
            ->where(['address_sn'=>$address_sn,'address_status'=>0])
            ->find();
        if(empty($address_give))$this->error("发货单号[{$address_sn}]不存在");
        if(empty($address_give0))$this->error("发货单号[{$address_sn}]已装车完成");

        //定时任务，超过24小时未确认发货，则自动发货
        GiveModel::taskSubGiveAddress($address_give['address_sn'],time());

        $this->success('操作成功','','_parent_reload');
    }
    //合并发货单
    public function deliverMerge()
    {
        //发货单号
        $address_sns = input('address_sns');
        if(empty($address_sns))$this->error('请选择发货单');
        if(strpos($address_sns, ',') === false)$this->error('请选择需要合并的发货单');

        $address_list = [];
        $formItems = [];

        $address_sns = explode(',',$address_sns);
        rsort($address_sns);
        $address_sn = '';
        $merge_address_give = [];

        foreach ($address_sns as $k=>$v){
            $address_give = Db::name('mill_order')
                ->alias('o')
                ->field('o.*,c.plate_number,g.address_status,g.car_id,g.address_sn')
                ->leftJoin('mill_order_archives_give g','g.order_id=o.id')
                ->leftJoin('mill_car c','g.car_id=c.id')
                ->where(['g.address_sn'=>$v])
                ->find();

            //发货单号列表
            $address_list[] = $address_give;

            //字段名
            $field = "merge_address_sn[{$k}]";
            //设置第一个发货单号为默认数据
            if($k == 0){
                $field = 'address_sn';
                $address_sn = $v;
                $merge_address_give = $address_give;
            }

            //判断是否符合合并发货单条件
            if($address_give['address_status'] == 0)$this->error("发货单号[{$address_sn}]还在装车中");
            if($address_give['order_id'] != $merge_address_give['order_id'])$this->error("发货单号[{$address_give['address_sn']}]与[{$merge_address_give['address_sn']}]不是同一批次",'','',5);
            if($address_give['car_id'] != $merge_address_give['car_id'])$this->error("发货单号[{$address_give['address_sn']}]与[{$merge_address_give['address_sn']}]不是同一批车辆",'','',5);

            $title = "发货单号：{$v} 车牌号：{$address_give['plate_number']} 档案号：{$address_give['archives_sn']} 工程名称：{$address_give['engineering']}";
            $formItems[] = ['static:12', $field,'',$title,$v,$v];
        }
        $address_title = "合并后新的发货单号：{$address_sn}";
        $formItems[] = ['static:12', "static1",'', $address_title];

        //CSS
        $css = '<style>
                    .help-block {
                        font-size: 15px;
                        color: black;
                        font-weight: bold;
                    }
                    .form-group {
                        text-align: center;
                    }
                    #form_group_static1 .help-block {
                        color: #3399ff;
                    }
                </style>';

        if ($this->request->isPost()){

            $address_sn = input('address_sn');
            //需要合并的发货单号
            $merge_address_sn = input('merge_address_sn');
            if(empty($merge_address_give))$this->error("请选择需要合并的发货单");

            $address_give = Db::name('mill_order_archives_give')->where(['address_sn'=>$address_sn])->find();

            $update = [
                'address_sn'        =>  $address_give['address_sn'],
                'address_status'    =>  $address_give['address_status'],
            ];
            if(!(Db::name('mill_order_archives_give')->where([['address_sn','in',$merge_address_sn]])->update($update))){

                Db::name('mill_order_archives_give_log')->where([['address_sn','in',$merge_address_sn]])->update($update);

                //更新发货金额
                FinanceModel::updateAddressPrice($address_give['order_id'],$address_give['address_sn']);
                FinanceModel::updateAddressPrice($merge_address_give['order_id'],$merge_address_sn);

                $this->error('操作失败');
            }

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        return ZBuilder::make('form')
            ->setPageTitle('合并发货单') // 页面标题
            // 批量添加表单项
            ->addFormItems($formItems)
            ->setExtraCss($css)
            ->fetch();
    }
    //补货OR卸货
    public function ableGive(){

        //获取发货部的产品状态
        $role_status = GiveModel::$last_give_status;
        //0:补货 1:卸货
        $type = intval(input('type'));
        //发货单号
        $address_sn = input('address_sn');
        if ($this->request->isPost()){

            $archives_sn = input('archives_sn');
            //同产品的信息
            $address_give_where = ['address_sn'=>$address_sn];
            if(!empty($archives_sn))$address_give_where['archives_sn'] = $archives_sn;
            $address_give = Db::name('mill_order_archives_give_log')
                ->where($address_give_where)
                ->order('status_time desc')
                ->find();
            $user = $address_give;
            $user['uid'] = $address_give['status_uid'];

            //勾选时的批量处理，即产品ID集合，数组格式
            $ids = input('ids');

            $give_search_post = input('give_search');
            $give_search_arr = str_replace("，",",",$give_search_post);

            if(!empty($ids))$give_search_arr = $ids;

            $give_search_arr = !is_array($give_search_arr)?explode(',',$give_search_arr):$give_search_arr;

            foreach ($give_search_arr as $v){
                //如果产品ID集合存在，则直接调用ID
                if(!empty($ids)){
                    $where = [
                        ['g.id','=',$v]
                    ];
                }
                else{
                    //序列号仅为数字时，则更新该序列号所有的产品
                    //如果格式为2-10，则仅更新该序列号的指定产品
                    $give_search = explode('-',$v);

                    $where = [
                        ['a.sort','=',$give_search[0]],
                        ['g.archives_sn','=',$address_give['archives_sn']],
                    ];
                    if(!empty($give_search[1]))$where[] = ['g.counter','=',$give_search[1]];
                }

                $give = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('g.*,g.status as give_status,a.one_area,a.number as archives_number,c.is_lock,o.client_id,o.status as order_status,o.is_lock as is_lock2,o.give_sort')
                    ->leftJoin('mill_order o','o.id=g.order_id')
                    ->leftJoin('mill_client c','c.id=o.client_id')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($where)
                    ->find();

                //统计是否全部发货完成，或未发货完成
                if(empty($type))$where[] = ['g.status','=',$role_status];
                else $where[] = ['g.status','<>',$role_status];
                $count = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('g.*')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($where)
                    ->count();

                if(empty($give))$this->error("该产品不存在[{$v}]");
                if(empty($type) && $count)$this->error("该产品已发货[{$v}]");
                elseif($type == 1 && $count)$this->error("该产品未发货[{$v}]");
                //验证该产品是否已冻结
                if($give['is_lock'] == 0 || $give['is_lock2'] == 0)$this->error("该工程已冻结，请联系管理员");
                //验证该产品是否已取消生产
                if($give['quality_status'] == -3)$this->error("该产品已取消生产");
                //验证该产品是否已取消生产工艺
                if(empty($give['give_sort']))$this->error("该工程未选择生产工艺");

            }

            foreach ($give_search_arr as $v){
                //如果产品ID集合存在，则直接调用ID
                if(!empty($ids)){
                    $where = [
                        ['g.id','=',$v]
                    ];
                }
                else{
                    //序列号仅为数字时，则更新该序列号所有的产品
                    //如果格式为2-10，则仅更新该序列号的指定产品
                    $give_search = explode('-',$v);

                    $where = [
                        ['a.sort','=',$give_search[0]],
                        ['g.archives_sn','=',$address_give['archives_sn']],
                    ];
                    if(!empty($give_search[1]))$where[] = ['g.counter','=',$give_search[1]];
                }

                $give = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('g.*,g.status as give_status,a.one_area,a.number as archives_number,c.is_lock,o.client_id,o.status as order_status,o.is_lock as is_lock2,o.give_sort')
                    ->leftJoin('mill_order o','o.id=g.order_id')
                    ->leftJoin('mill_client c','c.id=o.client_id')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($where)
                    ->group('g.id')
                    ->find();
                $give['is_address'] = 1;

                //补货
                if(empty($type)){

                    //同步同产品的发货信息
                    $update = [
                        'address_sn'        =>  $address_give['address_sn'],
                        'address_date'      =>  $address_give['address_date'],
                        'address_time'      =>  $address_give['address_time'],
                        'address_status'    =>  $address_give['address_status'],
                        'car_id'            =>  $address_give['car_id'],
                    ];
                    //补上各流水线状态，默认当前操作部门用户
                    $give = array_merge($give,$update);

                    //------------补扫情况，自动补满之前所有状态-------------
                    $sup_status = $role_status;//需要补充到的状态
                    $save = GiveModel::giveToStatus($user,$sup_status,$give);
                    $log_list = isset($save['log_list'])?$save['log_list']:'';

                    $save = array_merge($save,$update);

                    $give['status'] = $save['status'];

                    unset($save['log_list']);
                    //----------补扫情况，自动补满之前所有状态 END----------

                    $give_where = ['id'=>$give['id']];
                    if(Db::name('mill_order_archives_give')->where($give_where)->update($save)){
                        //生成扫码记录
                        GiveModel::addGiveLog($log_list);
                        //检查更新产品主体状态
                        ArchivesModel::checkStatus($give,$role_status);
                    }

                }
                //卸货
                elseif ($type == 1){

                    $give_srot = explode(',',$give['give_sort']);
                    array_pop($give_srot);
                    $status = end($give_srot);

                    $last_give_where = ['order_id'=>$give['order_id'],'status'=>$status];
                    $last_give = Db::name('mill_order_archives_give_log')
                        ->where($last_give_where)
                        ->order('status_time desc')
                        ->find();

                    //同步同产品的发货信息
                    $save = [
                        'status'            =>  $status,
                        'status_uid'        =>  $last_give['status_uid'],
                        'status_time'       =>  $last_give['status_time'],
                        'address_sn'        =>  '',
                        'address_date'      =>  '',
                        'address_time'      =>  '',
                        'address_status'    =>  0,
                        'car_id'            =>  '',
                    ];
                    $save["status{$role_status}_time"] = '';

                    $give_where = ['id'=>$give['id']];
                    if(Db::name('mill_order_archives_give')->where($give_where)->update($save)){

                        //删除发货的扫码记录
                        $delete_give_where = ['give_id'=>$give['id'],'status'=>$role_status];
                        Db::name('mill_order_archives_give_log')->where($delete_give_where)->delete();
                        //检查更新产品主体状态
                        ArchivesModel::checkStatus($give,$role_status);
                    }
                }

            }

            //更新发货金额
            FinanceModel::updateAddressPrice($address_give['order_id'],$address_give['address_sn']);

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        //根据发货单号获取批次
        $batch = Db::name('mill_order_archives_give')->where(['address_sn'=>$address_sn])->group('archives_sn')->column('archives_sn as archives_sns','archives_sn');
        return ZBuilder::make('form')
            ->setPageTitle('补货') // 页面标题
            ->addStatic('address_sn', '发货单号', '', $address_sn,$address_sn)
            ->addHidden('type',$type)
            ->addFormItems([ // 批量添加表单项
                //['text:||||must', 'address_sn','发货单号', $address_sn],
                ['select:||||must', 'archives_sn', '档案编号','',$batch,key($batch)],
                ['text:||||must', 'give_search', '产品序列号'],
            ])
            ->submitConfirm()
            ->layout(['address_sn'=>12,'archives_sn'=>12,'give_search'=>12])
            ->fetch();

    }
}
